Make TargetTransformInfo keeping a reference to the Module DataLayout
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
72                        SDValue V2);
73
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75                                      const X86Subtarget &STI)
76     : TargetLowering(TM), Subtarget(&STI) {
77   X86ScalarSSEf64 = Subtarget->hasSSE2();
78   X86ScalarSSEf32 = Subtarget->hasSSE1();
79   TD = getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
209   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210   // are Legal, f80 is custom lowered.
211   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248   }
249
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1037   }
1038
1039   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1061     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1062     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1076
1077     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078     // even though v8i16 is a legal type.
1079     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1082
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1085     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1086
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1088     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1089
1090     for (MVT VT : MVT::fp_vector_valuetypes())
1091       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1092
1093     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1106
1107     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1109     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1110
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1128
1129     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1136     }
1137
1138     if (Subtarget->hasInt256()) {
1139       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1143
1144       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1148
1149       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1150       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1153
1154       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1156       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1157       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1158
1159       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1161       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1171
1172       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173       // when we have a 256bit-wide blend with immediate.
1174       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1175
1176       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1183
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1190     } else {
1191       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1195
1196       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1200
1201       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1205     }
1206
1207     // In the customized shift lowering, the legal cases in AVX2 will be
1208     // recognized.
1209     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1210     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1211
1212     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (MVT VT : MVT::vector_valuetypes()) {
1220       if (VT.getScalarSizeInBits() >= 32) {
1221         setOperationAction(ISD::MLOAD,  VT, Legal);
1222         setOperationAction(ISD::MSTORE, VT, Legal);
1223       }
1224       // Extract subvector is special because the value type
1225       // (result) is 128-bit but the source is 256-bit wide.
1226       if (VT.is128BitVector()) {
1227         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228       }
1229       // Do not attempt to custom lower other non-256-bit vectors
1230       if (!VT.is256BitVector())
1231         continue;
1232
1233       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1234       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1235       setOperationAction(ISD::VSELECT,            VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     if (Subtarget->hasInt256())
1244       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1245
1246
1247     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249       MVT VT = (MVT::SimpleValueType)i;
1250
1251       // Do not attempt to promote non-256-bit vectors
1252       if (!VT.is256BitVector())
1253         continue;
1254
1255       setOperationAction(ISD::AND,    VT, Promote);
1256       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1257       setOperationAction(ISD::OR,     VT, Promote);
1258       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1259       setOperationAction(ISD::XOR,    VT, Promote);
1260       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1261       setOperationAction(ISD::LOAD,   VT, Promote);
1262       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1263       setOperationAction(ISD::SELECT, VT, Promote);
1264       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265     }
1266   }
1267
1268   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1272     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1273
1274     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1275     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1276     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1277
1278     for (MVT VT : MVT::fp_vector_valuetypes())
1279       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1280
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1291     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1292     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1293
1294     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1295     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1296     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1297     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1298     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1299     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1300     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1301     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1302     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1305     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1306     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1307
1308     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1313     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1314
1315     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1321     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1323
1324     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1325     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1326     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1328     if (Subtarget->is64Bit()) {
1329       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1330       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1331       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1332       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1333     }
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1348     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1349     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1350
1351     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1352     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1353     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1354     if (Subtarget->hasDQI()) {
1355       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1356       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1357     }
1358     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1359     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1360     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1361     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1362     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1363     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1364     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1365     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1366     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1367     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1368     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1369     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1370     if (Subtarget->hasDQI()) {
1371       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1372       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1373     }
1374     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1375     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1376     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1377     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1378     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1379     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1380     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1381     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1382     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1383     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1384
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1390
1391     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1392     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1393
1394     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1395
1396     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1397     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1399     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1400     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1401     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1402     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1403     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1404     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1405     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1406     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1407
1408     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1409     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1410     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1411     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1412     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1413     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1414     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1415     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1416
1417     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1418     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1419
1420     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1421     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1422
1423     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1424
1425     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1426     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1427
1428     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1429     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1430
1431     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1432     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1433
1434     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1435     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1436     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1437     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1438     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1439     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1440
1441     if (Subtarget->hasCDI()) {
1442       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1443       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1444     }
1445     if (Subtarget->hasDQI()) {
1446       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1447       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1448       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1449     }
1450     // Custom lower several nodes.
1451     for (MVT VT : MVT::vector_valuetypes()) {
1452       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453       if (EltSize == 1) {
1454         setOperationAction(ISD::AND, VT, Legal);
1455         setOperationAction(ISD::OR,  VT, Legal);
1456         setOperationAction(ISD::XOR,  VT, Legal);
1457       }
1458       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1459         setOperationAction(ISD::MGATHER,  VT, Custom);
1460         setOperationAction(ISD::MSCATTER, VT, Custom);
1461       }
1462       // Extract subvector is special because the value type
1463       // (result) is 256/128-bit but the source is 512-bit wide.
1464       if (VT.is128BitVector() || VT.is256BitVector()) {
1465         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1466       }
1467       if (VT.getVectorElementType() == MVT::i1)
1468         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1469
1470       // Do not attempt to custom lower other non-512-bit vectors
1471       if (!VT.is512BitVector())
1472         continue;
1473
1474       if (EltSize >= 32) {
1475         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1476         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1477         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1478         setOperationAction(ISD::VSELECT,             VT, Legal);
1479         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1480         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1481         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1482         setOperationAction(ISD::MLOAD,               VT, Legal);
1483         setOperationAction(ISD::MSTORE,              VT, Legal);
1484       }
1485     }
1486     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1487       MVT VT = (MVT::SimpleValueType)i;
1488
1489       // Do not attempt to promote non-512-bit vectors.
1490       if (!VT.is512BitVector())
1491         continue;
1492
1493       setOperationAction(ISD::SELECT, VT, Promote);
1494       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1495     }
1496   }// has  AVX-512
1497
1498   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1499     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1500     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1501
1502     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1503     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1504
1505     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1506     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1507     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1508     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1509     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1510     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1511     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1512     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1513     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1514     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1515     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1516     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1517     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1518     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1519     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1520     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1521     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1522     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1523     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1524     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1525     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1526     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1527     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1528     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1529     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1530     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1531     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1532     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1533     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1534
1535     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1536     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1537     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1538     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1539     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1540     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1541     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1542     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1543
1544     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1545       const MVT VT = (MVT::SimpleValueType)i;
1546
1547       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1548
1549       // Do not attempt to promote non-512-bit vectors.
1550       if (!VT.is512BitVector())
1551         continue;
1552
1553       if (EltSize < 32) {
1554         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1555         setOperationAction(ISD::VSELECT,             VT, Legal);
1556       }
1557     }
1558   }
1559
1560   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1561     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1562     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1563
1564     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1565     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1566     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1567     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1568     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1569     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1570     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1571     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1572     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1573     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1574
1575     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1576     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1577     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1578     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1579     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1580     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1581     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1582     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1583
1584     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1585     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1586     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1587     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1588     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1589     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1590     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1591     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1592   }
1593
1594   // We want to custom lower some of our intrinsics.
1595   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1596   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1597   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1598   if (!Subtarget->is64Bit())
1599     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1600
1601   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1602   // handle type legalization for these operations here.
1603   //
1604   // FIXME: We really should do custom legalization for addition and
1605   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1606   // than generic legalization for 64-bit multiplication-with-overflow, though.
1607   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1608     // Add/Sub/Mul with overflow operations are custom lowered.
1609     MVT VT = IntVTs[i];
1610     setOperationAction(ISD::SADDO, VT, Custom);
1611     setOperationAction(ISD::UADDO, VT, Custom);
1612     setOperationAction(ISD::SSUBO, VT, Custom);
1613     setOperationAction(ISD::USUBO, VT, Custom);
1614     setOperationAction(ISD::SMULO, VT, Custom);
1615     setOperationAction(ISD::UMULO, VT, Custom);
1616   }
1617
1618
1619   if (!Subtarget->is64Bit()) {
1620     // These libcalls are not available in 32-bit.
1621     setLibcallName(RTLIB::SHL_I128, nullptr);
1622     setLibcallName(RTLIB::SRL_I128, nullptr);
1623     setLibcallName(RTLIB::SRA_I128, nullptr);
1624   }
1625
1626   // Combine sin / cos into one node or libcall if possible.
1627   if (Subtarget->hasSinCos()) {
1628     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1629     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1630     if (Subtarget->isTargetDarwin()) {
1631       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1632       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1633       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1634       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1635     }
1636   }
1637
1638   if (Subtarget->isTargetWin64()) {
1639     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1640     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1641     setOperationAction(ISD::SREM, MVT::i128, Custom);
1642     setOperationAction(ISD::UREM, MVT::i128, Custom);
1643     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1644     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1645   }
1646
1647   // We have target-specific dag combine patterns for the following nodes:
1648   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1649   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1650   setTargetDAGCombine(ISD::BITCAST);
1651   setTargetDAGCombine(ISD::VSELECT);
1652   setTargetDAGCombine(ISD::SELECT);
1653   setTargetDAGCombine(ISD::SHL);
1654   setTargetDAGCombine(ISD::SRA);
1655   setTargetDAGCombine(ISD::SRL);
1656   setTargetDAGCombine(ISD::OR);
1657   setTargetDAGCombine(ISD::AND);
1658   setTargetDAGCombine(ISD::ADD);
1659   setTargetDAGCombine(ISD::FADD);
1660   setTargetDAGCombine(ISD::FSUB);
1661   setTargetDAGCombine(ISD::FMA);
1662   setTargetDAGCombine(ISD::SUB);
1663   setTargetDAGCombine(ISD::LOAD);
1664   setTargetDAGCombine(ISD::MLOAD);
1665   setTargetDAGCombine(ISD::STORE);
1666   setTargetDAGCombine(ISD::MSTORE);
1667   setTargetDAGCombine(ISD::ZERO_EXTEND);
1668   setTargetDAGCombine(ISD::ANY_EXTEND);
1669   setTargetDAGCombine(ISD::SIGN_EXTEND);
1670   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1671   setTargetDAGCombine(ISD::SINT_TO_FP);
1672   setTargetDAGCombine(ISD::UINT_TO_FP);
1673   setTargetDAGCombine(ISD::SETCC);
1674   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1675   setTargetDAGCombine(ISD::BUILD_VECTOR);
1676   setTargetDAGCombine(ISD::MUL);
1677   setTargetDAGCombine(ISD::XOR);
1678
1679   computeRegisterProperties(Subtarget->getRegisterInfo());
1680
1681   // On Darwin, -Os means optimize for size without hurting performance,
1682   // do not reduce the limit.
1683   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1684   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1685   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1686   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1687   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1688   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1689   setPrefLoopAlignment(4); // 2^4 bytes.
1690
1691   // Predictable cmov don't hurt on atom because it's in-order.
1692   PredictableSelectIsExpensive = !Subtarget->isAtom();
1693   EnableExtLdPromotion = true;
1694   setPrefFunctionAlignment(4); // 2^4 bytes.
1695
1696   verifyIntrinsicTables();
1697 }
1698
1699 // This has so far only been implemented for 64-bit MachO.
1700 bool X86TargetLowering::useLoadStackGuardNode() const {
1701   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1702 }
1703
1704 TargetLoweringBase::LegalizeTypeAction
1705 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1706   if (ExperimentalVectorWideningLegalization &&
1707       VT.getVectorNumElements() != 1 &&
1708       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1709     return TypeWidenVector;
1710
1711   return TargetLoweringBase::getPreferredVectorAction(VT);
1712 }
1713
1714 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1715   if (!VT.isVector())
1716     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1717
1718   const unsigned NumElts = VT.getVectorNumElements();
1719   const EVT EltVT = VT.getVectorElementType();
1720   if (VT.is512BitVector()) {
1721     if (Subtarget->hasAVX512())
1722       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1723           EltVT == MVT::f32 || EltVT == MVT::f64)
1724         switch(NumElts) {
1725         case  8: return MVT::v8i1;
1726         case 16: return MVT::v16i1;
1727       }
1728     if (Subtarget->hasBWI())
1729       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1730         switch(NumElts) {
1731         case 32: return MVT::v32i1;
1732         case 64: return MVT::v64i1;
1733       }
1734   }
1735
1736   if (VT.is256BitVector() || VT.is128BitVector()) {
1737     if (Subtarget->hasVLX())
1738       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1739           EltVT == MVT::f32 || EltVT == MVT::f64)
1740         switch(NumElts) {
1741         case 2: return MVT::v2i1;
1742         case 4: return MVT::v4i1;
1743         case 8: return MVT::v8i1;
1744       }
1745     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1746       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1747         switch(NumElts) {
1748         case  8: return MVT::v8i1;
1749         case 16: return MVT::v16i1;
1750         case 32: return MVT::v32i1;
1751       }
1752   }
1753
1754   return VT.changeVectorElementTypeToInteger();
1755 }
1756
1757 /// Helper for getByValTypeAlignment to determine
1758 /// the desired ByVal argument alignment.
1759 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1760   if (MaxAlign == 16)
1761     return;
1762   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1763     if (VTy->getBitWidth() == 128)
1764       MaxAlign = 16;
1765   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1766     unsigned EltAlign = 0;
1767     getMaxByValAlign(ATy->getElementType(), EltAlign);
1768     if (EltAlign > MaxAlign)
1769       MaxAlign = EltAlign;
1770   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1771     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1772       unsigned EltAlign = 0;
1773       getMaxByValAlign(STy->getElementType(i), EltAlign);
1774       if (EltAlign > MaxAlign)
1775         MaxAlign = EltAlign;
1776       if (MaxAlign == 16)
1777         break;
1778     }
1779   }
1780 }
1781
1782 /// Return the desired alignment for ByVal aggregate
1783 /// function arguments in the caller parameter area. For X86, aggregates
1784 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1785 /// are at 4-byte boundaries.
1786 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1787   if (Subtarget->is64Bit()) {
1788     // Max of 8 and alignment of type.
1789     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1790     if (TyAlign > 8)
1791       return TyAlign;
1792     return 8;
1793   }
1794
1795   unsigned Align = 4;
1796   if (Subtarget->hasSSE1())
1797     getMaxByValAlign(Ty, Align);
1798   return Align;
1799 }
1800
1801 /// Returns the target specific optimal type for load
1802 /// and store operations as a result of memset, memcpy, and memmove
1803 /// lowering. If DstAlign is zero that means it's safe to destination
1804 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1805 /// means there isn't a need to check it against alignment requirement,
1806 /// probably because the source does not need to be loaded. If 'IsMemset' is
1807 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1808 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1809 /// source is constant so it does not need to be loaded.
1810 /// It returns EVT::Other if the type should be determined using generic
1811 /// target-independent logic.
1812 EVT
1813 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1814                                        unsigned DstAlign, unsigned SrcAlign,
1815                                        bool IsMemset, bool ZeroMemset,
1816                                        bool MemcpyStrSrc,
1817                                        MachineFunction &MF) const {
1818   const Function *F = MF.getFunction();
1819   if ((!IsMemset || ZeroMemset) &&
1820       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1821     if (Size >= 16 &&
1822         (Subtarget->isUnalignedMemAccessFast() ||
1823          ((DstAlign == 0 || DstAlign >= 16) &&
1824           (SrcAlign == 0 || SrcAlign >= 16)))) {
1825       if (Size >= 32) {
1826         if (Subtarget->hasInt256())
1827           return MVT::v8i32;
1828         if (Subtarget->hasFp256())
1829           return MVT::v8f32;
1830       }
1831       if (Subtarget->hasSSE2())
1832         return MVT::v4i32;
1833       if (Subtarget->hasSSE1())
1834         return MVT::v4f32;
1835     } else if (!MemcpyStrSrc && Size >= 8 &&
1836                !Subtarget->is64Bit() &&
1837                Subtarget->hasSSE2()) {
1838       // Do not use f64 to lower memcpy if source is string constant. It's
1839       // better to use i32 to avoid the loads.
1840       return MVT::f64;
1841     }
1842   }
1843   if (Subtarget->is64Bit() && Size >= 8)
1844     return MVT::i64;
1845   return MVT::i32;
1846 }
1847
1848 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1849   if (VT == MVT::f32)
1850     return X86ScalarSSEf32;
1851   else if (VT == MVT::f64)
1852     return X86ScalarSSEf64;
1853   return true;
1854 }
1855
1856 bool
1857 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1858                                                   unsigned,
1859                                                   unsigned,
1860                                                   bool *Fast) const {
1861   if (Fast)
1862     *Fast = Subtarget->isUnalignedMemAccessFast();
1863   return true;
1864 }
1865
1866 /// Return the entry encoding for a jump table in the
1867 /// current function.  The returned value is a member of the
1868 /// MachineJumpTableInfo::JTEntryKind enum.
1869 unsigned X86TargetLowering::getJumpTableEncoding() const {
1870   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1871   // symbol.
1872   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1873       Subtarget->isPICStyleGOT())
1874     return MachineJumpTableInfo::EK_Custom32;
1875
1876   // Otherwise, use the normal jump table encoding heuristics.
1877   return TargetLowering::getJumpTableEncoding();
1878 }
1879
1880 bool X86TargetLowering::useSoftFloat() const {
1881   return Subtarget->useSoftFloat();
1882 }
1883
1884 const MCExpr *
1885 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1886                                              const MachineBasicBlock *MBB,
1887                                              unsigned uid,MCContext &Ctx) const{
1888   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1889          Subtarget->isPICStyleGOT());
1890   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1891   // entries.
1892   return MCSymbolRefExpr::create(MBB->getSymbol(),
1893                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1894 }
1895
1896 /// Returns relocation base for the given PIC jumptable.
1897 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1898                                                     SelectionDAG &DAG) const {
1899   if (!Subtarget->is64Bit())
1900     // This doesn't have SDLoc associated with it, but is not really the
1901     // same as a Register.
1902     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1903   return Table;
1904 }
1905
1906 /// This returns the relocation base for the given PIC jumptable,
1907 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1908 const MCExpr *X86TargetLowering::
1909 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1910                              MCContext &Ctx) const {
1911   // X86-64 uses RIP relative addressing based on the jump table label.
1912   if (Subtarget->isPICStyleRIPRel())
1913     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1914
1915   // Otherwise, the reference is relative to the PIC base.
1916   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1917 }
1918
1919 std::pair<const TargetRegisterClass *, uint8_t>
1920 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1921                                            MVT VT) const {
1922   const TargetRegisterClass *RRC = nullptr;
1923   uint8_t Cost = 1;
1924   switch (VT.SimpleTy) {
1925   default:
1926     return TargetLowering::findRepresentativeClass(TRI, VT);
1927   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1928     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1929     break;
1930   case MVT::x86mmx:
1931     RRC = &X86::VR64RegClass;
1932     break;
1933   case MVT::f32: case MVT::f64:
1934   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1935   case MVT::v4f32: case MVT::v2f64:
1936   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1937   case MVT::v4f64:
1938     RRC = &X86::VR128RegClass;
1939     break;
1940   }
1941   return std::make_pair(RRC, Cost);
1942 }
1943
1944 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1945                                                unsigned &Offset) const {
1946   if (!Subtarget->isTargetLinux())
1947     return false;
1948
1949   if (Subtarget->is64Bit()) {
1950     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1951     Offset = 0x28;
1952     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1953       AddressSpace = 256;
1954     else
1955       AddressSpace = 257;
1956   } else {
1957     // %gs:0x14 on i386
1958     Offset = 0x14;
1959     AddressSpace = 256;
1960   }
1961   return true;
1962 }
1963
1964 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1965                                             unsigned DestAS) const {
1966   assert(SrcAS != DestAS && "Expected different address spaces!");
1967
1968   return SrcAS < 256 && DestAS < 256;
1969 }
1970
1971 //===----------------------------------------------------------------------===//
1972 //               Return Value Calling Convention Implementation
1973 //===----------------------------------------------------------------------===//
1974
1975 #include "X86GenCallingConv.inc"
1976
1977 bool
1978 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1979                                   MachineFunction &MF, bool isVarArg,
1980                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1981                         LLVMContext &Context) const {
1982   SmallVector<CCValAssign, 16> RVLocs;
1983   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1984   return CCInfo.CheckReturn(Outs, RetCC_X86);
1985 }
1986
1987 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1988   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1989   return ScratchRegs;
1990 }
1991
1992 SDValue
1993 X86TargetLowering::LowerReturn(SDValue Chain,
1994                                CallingConv::ID CallConv, bool isVarArg,
1995                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1996                                const SmallVectorImpl<SDValue> &OutVals,
1997                                SDLoc dl, SelectionDAG &DAG) const {
1998   MachineFunction &MF = DAG.getMachineFunction();
1999   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2000
2001   SmallVector<CCValAssign, 16> RVLocs;
2002   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2003   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2004
2005   SDValue Flag;
2006   SmallVector<SDValue, 6> RetOps;
2007   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2008   // Operand #1 = Bytes To Pop
2009   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2010                    MVT::i16));
2011
2012   // Copy the result values into the output registers.
2013   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2014     CCValAssign &VA = RVLocs[i];
2015     assert(VA.isRegLoc() && "Can only return in registers!");
2016     SDValue ValToCopy = OutVals[i];
2017     EVT ValVT = ValToCopy.getValueType();
2018
2019     // Promote values to the appropriate types.
2020     if (VA.getLocInfo() == CCValAssign::SExt)
2021       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2022     else if (VA.getLocInfo() == CCValAssign::ZExt)
2023       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2024     else if (VA.getLocInfo() == CCValAssign::AExt) {
2025       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2026         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2027       else
2028         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2029     }
2030     else if (VA.getLocInfo() == CCValAssign::BCvt)
2031       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2032
2033     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2034            "Unexpected FP-extend for return value.");
2035
2036     // If this is x86-64, and we disabled SSE, we can't return FP values,
2037     // or SSE or MMX vectors.
2038     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2039          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2040           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2041       report_fatal_error("SSE register return with SSE disabled");
2042     }
2043     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2044     // llvm-gcc has never done it right and no one has noticed, so this
2045     // should be OK for now.
2046     if (ValVT == MVT::f64 &&
2047         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2048       report_fatal_error("SSE2 register return with SSE2 disabled");
2049
2050     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2051     // the RET instruction and handled by the FP Stackifier.
2052     if (VA.getLocReg() == X86::FP0 ||
2053         VA.getLocReg() == X86::FP1) {
2054       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2055       // change the value to the FP stack register class.
2056       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2057         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2058       RetOps.push_back(ValToCopy);
2059       // Don't emit a copytoreg.
2060       continue;
2061     }
2062
2063     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2064     // which is returned in RAX / RDX.
2065     if (Subtarget->is64Bit()) {
2066       if (ValVT == MVT::x86mmx) {
2067         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2068           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2069           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2070                                   ValToCopy);
2071           // If we don't have SSE2 available, convert to v4f32 so the generated
2072           // register is legal.
2073           if (!Subtarget->hasSSE2())
2074             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2075         }
2076       }
2077     }
2078
2079     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2080     Flag = Chain.getValue(1);
2081     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2082   }
2083
2084   // All x86 ABIs require that for returning structs by value we copy
2085   // the sret argument into %rax/%eax (depending on ABI) for the return.
2086   // We saved the argument into a virtual register in the entry block,
2087   // so now we copy the value out and into %rax/%eax.
2088   //
2089   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2090   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2091   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2092   // either case FuncInfo->setSRetReturnReg() will have been called.
2093   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2094     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2095
2096     unsigned RetValReg
2097         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2098           X86::RAX : X86::EAX;
2099     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2100     Flag = Chain.getValue(1);
2101
2102     // RAX/EAX now acts like a return value.
2103     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2104   }
2105
2106   RetOps[0] = Chain;  // Update chain.
2107
2108   // Add the flag if we have it.
2109   if (Flag.getNode())
2110     RetOps.push_back(Flag);
2111
2112   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2113 }
2114
2115 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2116   if (N->getNumValues() != 1)
2117     return false;
2118   if (!N->hasNUsesOfValue(1, 0))
2119     return false;
2120
2121   SDValue TCChain = Chain;
2122   SDNode *Copy = *N->use_begin();
2123   if (Copy->getOpcode() == ISD::CopyToReg) {
2124     // If the copy has a glue operand, we conservatively assume it isn't safe to
2125     // perform a tail call.
2126     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2127       return false;
2128     TCChain = Copy->getOperand(0);
2129   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2130     return false;
2131
2132   bool HasRet = false;
2133   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2134        UI != UE; ++UI) {
2135     if (UI->getOpcode() != X86ISD::RET_FLAG)
2136       return false;
2137     // If we are returning more than one value, we can definitely
2138     // not make a tail call see PR19530
2139     if (UI->getNumOperands() > 4)
2140       return false;
2141     if (UI->getNumOperands() == 4 &&
2142         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2143       return false;
2144     HasRet = true;
2145   }
2146
2147   if (!HasRet)
2148     return false;
2149
2150   Chain = TCChain;
2151   return true;
2152 }
2153
2154 EVT
2155 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2156                                             ISD::NodeType ExtendKind) const {
2157   MVT ReturnMVT;
2158   // TODO: Is this also valid on 32-bit?
2159   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2160     ReturnMVT = MVT::i8;
2161   else
2162     ReturnMVT = MVT::i32;
2163
2164   EVT MinVT = getRegisterType(Context, ReturnMVT);
2165   return VT.bitsLT(MinVT) ? MinVT : VT;
2166 }
2167
2168 /// Lower the result values of a call into the
2169 /// appropriate copies out of appropriate physical registers.
2170 ///
2171 SDValue
2172 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2173                                    CallingConv::ID CallConv, bool isVarArg,
2174                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2175                                    SDLoc dl, SelectionDAG &DAG,
2176                                    SmallVectorImpl<SDValue> &InVals) const {
2177
2178   // Assign locations to each value returned by this call.
2179   SmallVector<CCValAssign, 16> RVLocs;
2180   bool Is64Bit = Subtarget->is64Bit();
2181   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2182                  *DAG.getContext());
2183   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2184
2185   // Copy all of the result registers out of their specified physreg.
2186   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2187     CCValAssign &VA = RVLocs[i];
2188     EVT CopyVT = VA.getLocVT();
2189
2190     // If this is x86-64, and we disabled SSE, we can't return FP values
2191     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2192         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2193       report_fatal_error("SSE register return with SSE disabled");
2194     }
2195
2196     // If we prefer to use the value in xmm registers, copy it out as f80 and
2197     // use a truncate to move it from fp stack reg to xmm reg.
2198     bool RoundAfterCopy = false;
2199     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2200         isScalarFPTypeInSSEReg(VA.getValVT())) {
2201       CopyVT = MVT::f80;
2202       RoundAfterCopy = (CopyVT != VA.getLocVT());
2203     }
2204
2205     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2206                                CopyVT, InFlag).getValue(1);
2207     SDValue Val = Chain.getValue(0);
2208
2209     if (RoundAfterCopy)
2210       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2211                         // This truncation won't change the value.
2212                         DAG.getIntPtrConstant(1, dl));
2213
2214     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2215       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2216
2217     InFlag = Chain.getValue(2);
2218     InVals.push_back(Val);
2219   }
2220
2221   return Chain;
2222 }
2223
2224 //===----------------------------------------------------------------------===//
2225 //                C & StdCall & Fast Calling Convention implementation
2226 //===----------------------------------------------------------------------===//
2227 //  StdCall calling convention seems to be standard for many Windows' API
2228 //  routines and around. It differs from C calling convention just a little:
2229 //  callee should clean up the stack, not caller. Symbols should be also
2230 //  decorated in some fancy way :) It doesn't support any vector arguments.
2231 //  For info on fast calling convention see Fast Calling Convention (tail call)
2232 //  implementation LowerX86_32FastCCCallTo.
2233
2234 /// CallIsStructReturn - Determines whether a call uses struct return
2235 /// semantics.
2236 enum StructReturnType {
2237   NotStructReturn,
2238   RegStructReturn,
2239   StackStructReturn
2240 };
2241 static StructReturnType
2242 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2243   if (Outs.empty())
2244     return NotStructReturn;
2245
2246   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2247   if (!Flags.isSRet())
2248     return NotStructReturn;
2249   if (Flags.isInReg())
2250     return RegStructReturn;
2251   return StackStructReturn;
2252 }
2253
2254 /// Determines whether a function uses struct return semantics.
2255 static StructReturnType
2256 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2257   if (Ins.empty())
2258     return NotStructReturn;
2259
2260   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2261   if (!Flags.isSRet())
2262     return NotStructReturn;
2263   if (Flags.isInReg())
2264     return RegStructReturn;
2265   return StackStructReturn;
2266 }
2267
2268 /// Make a copy of an aggregate at address specified by "Src" to address
2269 /// "Dst" with size and alignment information specified by the specific
2270 /// parameter attribute. The copy will be passed as a byval function parameter.
2271 static SDValue
2272 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2273                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2274                           SDLoc dl) {
2275   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2276
2277   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2278                        /*isVolatile*/false, /*AlwaysInline=*/true,
2279                        /*isTailCall*/false,
2280                        MachinePointerInfo(), MachinePointerInfo());
2281 }
2282
2283 /// Return true if the calling convention is one that
2284 /// supports tail call optimization.
2285 static bool IsTailCallConvention(CallingConv::ID CC) {
2286   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2287           CC == CallingConv::HiPE);
2288 }
2289
2290 /// \brief Return true if the calling convention is a C calling convention.
2291 static bool IsCCallConvention(CallingConv::ID CC) {
2292   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2293           CC == CallingConv::X86_64_SysV);
2294 }
2295
2296 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2297   auto Attr =
2298       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2299   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2300     return false;
2301
2302   CallSite CS(CI);
2303   CallingConv::ID CalleeCC = CS.getCallingConv();
2304   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2305     return false;
2306
2307   return true;
2308 }
2309
2310 /// Return true if the function is being made into
2311 /// a tailcall target by changing its ABI.
2312 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2313                                    bool GuaranteedTailCallOpt) {
2314   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2315 }
2316
2317 SDValue
2318 X86TargetLowering::LowerMemArgument(SDValue Chain,
2319                                     CallingConv::ID CallConv,
2320                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2321                                     SDLoc dl, SelectionDAG &DAG,
2322                                     const CCValAssign &VA,
2323                                     MachineFrameInfo *MFI,
2324                                     unsigned i) const {
2325   // Create the nodes corresponding to a load from this parameter slot.
2326   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2327   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2328       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2329   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2330   EVT ValVT;
2331
2332   // If value is passed by pointer we have address passed instead of the value
2333   // itself.
2334   bool ExtendedInMem = VA.isExtInLoc() &&
2335     VA.getValVT().getScalarType() == MVT::i1;
2336
2337   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2338     ValVT = VA.getLocVT();
2339   else
2340     ValVT = VA.getValVT();
2341
2342   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2343   // changed with more analysis.
2344   // In case of tail call optimization mark all arguments mutable. Since they
2345   // could be overwritten by lowering of arguments in case of a tail call.
2346   if (Flags.isByVal()) {
2347     unsigned Bytes = Flags.getByValSize();
2348     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2349     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2350     return DAG.getFrameIndex(FI, getPointerTy());
2351   } else {
2352     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2353                                     VA.getLocMemOffset(), isImmutable);
2354     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2355     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2356                                MachinePointerInfo::getFixedStack(FI),
2357                                false, false, false, 0);
2358     return ExtendedInMem ?
2359       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2360   }
2361 }
2362
2363 // FIXME: Get this from tablegen.
2364 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2365                                                 const X86Subtarget *Subtarget) {
2366   assert(Subtarget->is64Bit());
2367
2368   if (Subtarget->isCallingConvWin64(CallConv)) {
2369     static const MCPhysReg GPR64ArgRegsWin64[] = {
2370       X86::RCX, X86::RDX, X86::R8,  X86::R9
2371     };
2372     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2373   }
2374
2375   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2376     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2377   };
2378   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2379 }
2380
2381 // FIXME: Get this from tablegen.
2382 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2383                                                 CallingConv::ID CallConv,
2384                                                 const X86Subtarget *Subtarget) {
2385   assert(Subtarget->is64Bit());
2386   if (Subtarget->isCallingConvWin64(CallConv)) {
2387     // The XMM registers which might contain var arg parameters are shadowed
2388     // in their paired GPR.  So we only need to save the GPR to their home
2389     // slots.
2390     // TODO: __vectorcall will change this.
2391     return None;
2392   }
2393
2394   const Function *Fn = MF.getFunction();
2395   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2396   bool isSoftFloat = Subtarget->useSoftFloat();
2397   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2398          "SSE register cannot be used when SSE is disabled!");
2399   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2400     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2401     // registers.
2402     return None;
2403
2404   static const MCPhysReg XMMArgRegs64Bit[] = {
2405     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2406     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2407   };
2408   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2409 }
2410
2411 SDValue
2412 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2413                                         CallingConv::ID CallConv,
2414                                         bool isVarArg,
2415                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2416                                         SDLoc dl,
2417                                         SelectionDAG &DAG,
2418                                         SmallVectorImpl<SDValue> &InVals)
2419                                           const {
2420   MachineFunction &MF = DAG.getMachineFunction();
2421   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2422   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2423
2424   const Function* Fn = MF.getFunction();
2425   if (Fn->hasExternalLinkage() &&
2426       Subtarget->isTargetCygMing() &&
2427       Fn->getName() == "main")
2428     FuncInfo->setForceFramePointer(true);
2429
2430   MachineFrameInfo *MFI = MF.getFrameInfo();
2431   bool Is64Bit = Subtarget->is64Bit();
2432   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2433
2434   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2435          "Var args not supported with calling convention fastcc, ghc or hipe");
2436
2437   // Assign locations to all of the incoming arguments.
2438   SmallVector<CCValAssign, 16> ArgLocs;
2439   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2440
2441   // Allocate shadow area for Win64
2442   if (IsWin64)
2443     CCInfo.AllocateStack(32, 8);
2444
2445   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2446
2447   unsigned LastVal = ~0U;
2448   SDValue ArgValue;
2449   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2450     CCValAssign &VA = ArgLocs[i];
2451     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2452     // places.
2453     assert(VA.getValNo() != LastVal &&
2454            "Don't support value assigned to multiple locs yet");
2455     (void)LastVal;
2456     LastVal = VA.getValNo();
2457
2458     if (VA.isRegLoc()) {
2459       EVT RegVT = VA.getLocVT();
2460       const TargetRegisterClass *RC;
2461       if (RegVT == MVT::i32)
2462         RC = &X86::GR32RegClass;
2463       else if (Is64Bit && RegVT == MVT::i64)
2464         RC = &X86::GR64RegClass;
2465       else if (RegVT == MVT::f32)
2466         RC = &X86::FR32RegClass;
2467       else if (RegVT == MVT::f64)
2468         RC = &X86::FR64RegClass;
2469       else if (RegVT.is512BitVector())
2470         RC = &X86::VR512RegClass;
2471       else if (RegVT.is256BitVector())
2472         RC = &X86::VR256RegClass;
2473       else if (RegVT.is128BitVector())
2474         RC = &X86::VR128RegClass;
2475       else if (RegVT == MVT::x86mmx)
2476         RC = &X86::VR64RegClass;
2477       else if (RegVT == MVT::i1)
2478         RC = &X86::VK1RegClass;
2479       else if (RegVT == MVT::v8i1)
2480         RC = &X86::VK8RegClass;
2481       else if (RegVT == MVT::v16i1)
2482         RC = &X86::VK16RegClass;
2483       else if (RegVT == MVT::v32i1)
2484         RC = &X86::VK32RegClass;
2485       else if (RegVT == MVT::v64i1)
2486         RC = &X86::VK64RegClass;
2487       else
2488         llvm_unreachable("Unknown argument type!");
2489
2490       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2491       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2492
2493       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2494       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2495       // right size.
2496       if (VA.getLocInfo() == CCValAssign::SExt)
2497         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2498                                DAG.getValueType(VA.getValVT()));
2499       else if (VA.getLocInfo() == CCValAssign::ZExt)
2500         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2501                                DAG.getValueType(VA.getValVT()));
2502       else if (VA.getLocInfo() == CCValAssign::BCvt)
2503         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2504
2505       if (VA.isExtInLoc()) {
2506         // Handle MMX values passed in XMM regs.
2507         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2508           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2509         else
2510           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2511       }
2512     } else {
2513       assert(VA.isMemLoc());
2514       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2515     }
2516
2517     // If value is passed via pointer - do a load.
2518     if (VA.getLocInfo() == CCValAssign::Indirect)
2519       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2520                              MachinePointerInfo(), false, false, false, 0);
2521
2522     InVals.push_back(ArgValue);
2523   }
2524
2525   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2526     // All x86 ABIs require that for returning structs by value we copy the
2527     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2528     // the argument into a virtual register so that we can access it from the
2529     // return points.
2530     if (Ins[i].Flags.isSRet()) {
2531       unsigned Reg = FuncInfo->getSRetReturnReg();
2532       if (!Reg) {
2533         MVT PtrTy = getPointerTy();
2534         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2535         FuncInfo->setSRetReturnReg(Reg);
2536       }
2537       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2538       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2539       break;
2540     }
2541   }
2542
2543   unsigned StackSize = CCInfo.getNextStackOffset();
2544   // Align stack specially for tail calls.
2545   if (FuncIsMadeTailCallSafe(CallConv,
2546                              MF.getTarget().Options.GuaranteedTailCallOpt))
2547     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2548
2549   // If the function takes variable number of arguments, make a frame index for
2550   // the start of the first vararg value... for expansion of llvm.va_start. We
2551   // can skip this if there are no va_start calls.
2552   if (MFI->hasVAStart() &&
2553       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2554                    CallConv != CallingConv::X86_ThisCall))) {
2555     FuncInfo->setVarArgsFrameIndex(
2556         MFI->CreateFixedObject(1, StackSize, true));
2557   }
2558
2559   MachineModuleInfo &MMI = MF.getMMI();
2560   const Function *WinEHParent = nullptr;
2561   if (MMI.hasWinEHFuncInfo(Fn))
2562     WinEHParent = MMI.getWinEHParent(Fn);
2563   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2564   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2565
2566   // Figure out if XMM registers are in use.
2567   assert(!(Subtarget->useSoftFloat() &&
2568            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2569          "SSE register cannot be used when SSE is disabled!");
2570
2571   // 64-bit calling conventions support varargs and register parameters, so we
2572   // have to do extra work to spill them in the prologue.
2573   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2574     // Find the first unallocated argument registers.
2575     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2576     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2577     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2578     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2579     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2580            "SSE register cannot be used when SSE is disabled!");
2581
2582     // Gather all the live in physical registers.
2583     SmallVector<SDValue, 6> LiveGPRs;
2584     SmallVector<SDValue, 8> LiveXMMRegs;
2585     SDValue ALVal;
2586     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2587       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2588       LiveGPRs.push_back(
2589           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2590     }
2591     if (!ArgXMMs.empty()) {
2592       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2593       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2594       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2595         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2596         LiveXMMRegs.push_back(
2597             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2598       }
2599     }
2600
2601     if (IsWin64) {
2602       // Get to the caller-allocated home save location.  Add 8 to account
2603       // for the return address.
2604       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2605       FuncInfo->setRegSaveFrameIndex(
2606           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2607       // Fixup to set vararg frame on shadow area (4 x i64).
2608       if (NumIntRegs < 4)
2609         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2610     } else {
2611       // For X86-64, if there are vararg parameters that are passed via
2612       // registers, then we must store them to their spots on the stack so
2613       // they may be loaded by deferencing the result of va_next.
2614       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2615       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2616       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2617           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2618     }
2619
2620     // Store the integer parameter registers.
2621     SmallVector<SDValue, 8> MemOps;
2622     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2623                                       getPointerTy());
2624     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2625     for (SDValue Val : LiveGPRs) {
2626       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2627                                 DAG.getIntPtrConstant(Offset, dl));
2628       SDValue Store =
2629         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2630                      MachinePointerInfo::getFixedStack(
2631                        FuncInfo->getRegSaveFrameIndex(), Offset),
2632                      false, false, 0);
2633       MemOps.push_back(Store);
2634       Offset += 8;
2635     }
2636
2637     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2638       // Now store the XMM (fp + vector) parameter registers.
2639       SmallVector<SDValue, 12> SaveXMMOps;
2640       SaveXMMOps.push_back(Chain);
2641       SaveXMMOps.push_back(ALVal);
2642       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2643                              FuncInfo->getRegSaveFrameIndex(), dl));
2644       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2645                              FuncInfo->getVarArgsFPOffset(), dl));
2646       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2647                         LiveXMMRegs.end());
2648       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2649                                    MVT::Other, SaveXMMOps));
2650     }
2651
2652     if (!MemOps.empty())
2653       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2654   } else if (IsWin64 && IsWinEHOutlined) {
2655     // Get to the caller-allocated home save location.  Add 8 to account
2656     // for the return address.
2657     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2658     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2659         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2660
2661     MMI.getWinEHFuncInfo(Fn)
2662         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2663         FuncInfo->getRegSaveFrameIndex();
2664
2665     // Store the second integer parameter (rdx) into rsp+16 relative to the
2666     // stack pointer at the entry of the function.
2667     SDValue RSFIN =
2668         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2669     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2670     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2671     Chain = DAG.getStore(
2672         Val.getValue(1), dl, Val, RSFIN,
2673         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2674         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2675   }
2676
2677   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2678     // Find the largest legal vector type.
2679     MVT VecVT = MVT::Other;
2680     // FIXME: Only some x86_32 calling conventions support AVX512.
2681     if (Subtarget->hasAVX512() &&
2682         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2683                      CallConv == CallingConv::Intel_OCL_BI)))
2684       VecVT = MVT::v16f32;
2685     else if (Subtarget->hasAVX())
2686       VecVT = MVT::v8f32;
2687     else if (Subtarget->hasSSE2())
2688       VecVT = MVT::v4f32;
2689
2690     // We forward some GPRs and some vector types.
2691     SmallVector<MVT, 2> RegParmTypes;
2692     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2693     RegParmTypes.push_back(IntVT);
2694     if (VecVT != MVT::Other)
2695       RegParmTypes.push_back(VecVT);
2696
2697     // Compute the set of forwarded registers. The rest are scratch.
2698     SmallVectorImpl<ForwardedRegister> &Forwards =
2699         FuncInfo->getForwardedMustTailRegParms();
2700     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2701
2702     // Conservatively forward AL on x86_64, since it might be used for varargs.
2703     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2704       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2705       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2706     }
2707
2708     // Copy all forwards from physical to virtual registers.
2709     for (ForwardedRegister &F : Forwards) {
2710       // FIXME: Can we use a less constrained schedule?
2711       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2712       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2713       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2714     }
2715   }
2716
2717   // Some CCs need callee pop.
2718   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2719                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2720     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2721   } else {
2722     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2723     // If this is an sret function, the return should pop the hidden pointer.
2724     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2725         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2726         argsAreStructReturn(Ins) == StackStructReturn)
2727       FuncInfo->setBytesToPopOnReturn(4);
2728   }
2729
2730   if (!Is64Bit) {
2731     // RegSaveFrameIndex is X86-64 only.
2732     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2733     if (CallConv == CallingConv::X86_FastCall ||
2734         CallConv == CallingConv::X86_ThisCall)
2735       // fastcc functions can't have varargs.
2736       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2737   }
2738
2739   FuncInfo->setArgumentStackSize(StackSize);
2740
2741   if (IsWinEHParent) {
2742     if (Is64Bit) {
2743       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2744       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2745       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2746       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2747       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2748                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2749                            /*isVolatile=*/true,
2750                            /*isNonTemporal=*/false, /*Alignment=*/0);
2751     } else {
2752       // Functions using Win32 EH are considered to have opaque SP adjustments
2753       // to force local variables to be addressed from the frame or base
2754       // pointers.
2755       MFI->setHasOpaqueSPAdjustment(true);
2756     }
2757   }
2758
2759   return Chain;
2760 }
2761
2762 SDValue
2763 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2764                                     SDValue StackPtr, SDValue Arg,
2765                                     SDLoc dl, SelectionDAG &DAG,
2766                                     const CCValAssign &VA,
2767                                     ISD::ArgFlagsTy Flags) const {
2768   unsigned LocMemOffset = VA.getLocMemOffset();
2769   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2770   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2771   if (Flags.isByVal())
2772     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2773
2774   return DAG.getStore(Chain, dl, Arg, PtrOff,
2775                       MachinePointerInfo::getStack(LocMemOffset),
2776                       false, false, 0);
2777 }
2778
2779 /// Emit a load of return address if tail call
2780 /// optimization is performed and it is required.
2781 SDValue
2782 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2783                                            SDValue &OutRetAddr, SDValue Chain,
2784                                            bool IsTailCall, bool Is64Bit,
2785                                            int FPDiff, SDLoc dl) const {
2786   // Adjust the Return address stack slot.
2787   EVT VT = getPointerTy();
2788   OutRetAddr = getReturnAddressFrameIndex(DAG);
2789
2790   // Load the "old" Return address.
2791   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2792                            false, false, false, 0);
2793   return SDValue(OutRetAddr.getNode(), 1);
2794 }
2795
2796 /// Emit a store of the return address if tail call
2797 /// optimization is performed and it is required (FPDiff!=0).
2798 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2799                                         SDValue Chain, SDValue RetAddrFrIdx,
2800                                         EVT PtrVT, unsigned SlotSize,
2801                                         int FPDiff, SDLoc dl) {
2802   // Store the return address to the appropriate stack slot.
2803   if (!FPDiff) return Chain;
2804   // Calculate the new stack slot for the return address.
2805   int NewReturnAddrFI =
2806     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2807                                          false);
2808   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2809   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2810                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2811                        false, false, 0);
2812   return Chain;
2813 }
2814
2815 SDValue
2816 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2817                              SmallVectorImpl<SDValue> &InVals) const {
2818   SelectionDAG &DAG                     = CLI.DAG;
2819   SDLoc &dl                             = CLI.DL;
2820   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2821   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2822   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2823   SDValue Chain                         = CLI.Chain;
2824   SDValue Callee                        = CLI.Callee;
2825   CallingConv::ID CallConv              = CLI.CallConv;
2826   bool &isTailCall                      = CLI.IsTailCall;
2827   bool isVarArg                         = CLI.IsVarArg;
2828
2829   MachineFunction &MF = DAG.getMachineFunction();
2830   bool Is64Bit        = Subtarget->is64Bit();
2831   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2832   StructReturnType SR = callIsStructReturn(Outs);
2833   bool IsSibcall      = false;
2834   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2835   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2836
2837   if (Attr.getValueAsString() == "true")
2838     isTailCall = false;
2839
2840   if (Subtarget->isPICStyleGOT() &&
2841       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2842     // If we are using a GOT, disable tail calls to external symbols with
2843     // default visibility. Tail calling such a symbol requires using a GOT
2844     // relocation, which forces early binding of the symbol. This breaks code
2845     // that require lazy function symbol resolution. Using musttail or
2846     // GuaranteedTailCallOpt will override this.
2847     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2848     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2849                G->getGlobal()->hasDefaultVisibility()))
2850       isTailCall = false;
2851   }
2852
2853   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2854   if (IsMustTail) {
2855     // Force this to be a tail call.  The verifier rules are enough to ensure
2856     // that we can lower this successfully without moving the return address
2857     // around.
2858     isTailCall = true;
2859   } else if (isTailCall) {
2860     // Check if it's really possible to do a tail call.
2861     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2862                     isVarArg, SR != NotStructReturn,
2863                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2864                     Outs, OutVals, Ins, DAG);
2865
2866     // Sibcalls are automatically detected tailcalls which do not require
2867     // ABI changes.
2868     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2869       IsSibcall = true;
2870
2871     if (isTailCall)
2872       ++NumTailCalls;
2873   }
2874
2875   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2876          "Var args not supported with calling convention fastcc, ghc or hipe");
2877
2878   // Analyze operands of the call, assigning locations to each operand.
2879   SmallVector<CCValAssign, 16> ArgLocs;
2880   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2881
2882   // Allocate shadow area for Win64
2883   if (IsWin64)
2884     CCInfo.AllocateStack(32, 8);
2885
2886   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2887
2888   // Get a count of how many bytes are to be pushed on the stack.
2889   unsigned NumBytes = CCInfo.getNextStackOffset();
2890   if (IsSibcall)
2891     // This is a sibcall. The memory operands are available in caller's
2892     // own caller's stack.
2893     NumBytes = 0;
2894   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2895            IsTailCallConvention(CallConv))
2896     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2897
2898   int FPDiff = 0;
2899   if (isTailCall && !IsSibcall && !IsMustTail) {
2900     // Lower arguments at fp - stackoffset + fpdiff.
2901     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2902
2903     FPDiff = NumBytesCallerPushed - NumBytes;
2904
2905     // Set the delta of movement of the returnaddr stackslot.
2906     // But only set if delta is greater than previous delta.
2907     if (FPDiff < X86Info->getTCReturnAddrDelta())
2908       X86Info->setTCReturnAddrDelta(FPDiff);
2909   }
2910
2911   unsigned NumBytesToPush = NumBytes;
2912   unsigned NumBytesToPop = NumBytes;
2913
2914   // If we have an inalloca argument, all stack space has already been allocated
2915   // for us and be right at the top of the stack.  We don't support multiple
2916   // arguments passed in memory when using inalloca.
2917   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2918     NumBytesToPush = 0;
2919     if (!ArgLocs.back().isMemLoc())
2920       report_fatal_error("cannot use inalloca attribute on a register "
2921                          "parameter");
2922     if (ArgLocs.back().getLocMemOffset() != 0)
2923       report_fatal_error("any parameter with the inalloca attribute must be "
2924                          "the only memory argument");
2925   }
2926
2927   if (!IsSibcall)
2928     Chain = DAG.getCALLSEQ_START(
2929         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2930
2931   SDValue RetAddrFrIdx;
2932   // Load return address for tail calls.
2933   if (isTailCall && FPDiff)
2934     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2935                                     Is64Bit, FPDiff, dl);
2936
2937   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2938   SmallVector<SDValue, 8> MemOpChains;
2939   SDValue StackPtr;
2940
2941   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2942   // of tail call optimization arguments are handle later.
2943   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2944   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2945     // Skip inalloca arguments, they have already been written.
2946     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2947     if (Flags.isInAlloca())
2948       continue;
2949
2950     CCValAssign &VA = ArgLocs[i];
2951     EVT RegVT = VA.getLocVT();
2952     SDValue Arg = OutVals[i];
2953     bool isByVal = Flags.isByVal();
2954
2955     // Promote the value if needed.
2956     switch (VA.getLocInfo()) {
2957     default: llvm_unreachable("Unknown loc info!");
2958     case CCValAssign::Full: break;
2959     case CCValAssign::SExt:
2960       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2961       break;
2962     case CCValAssign::ZExt:
2963       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2964       break;
2965     case CCValAssign::AExt:
2966       if (Arg.getValueType().isVector() &&
2967           Arg.getValueType().getScalarType() == MVT::i1)
2968         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2969       else if (RegVT.is128BitVector()) {
2970         // Special case: passing MMX values in XMM registers.
2971         Arg = DAG.getBitcast(MVT::i64, Arg);
2972         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2973         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2974       } else
2975         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2976       break;
2977     case CCValAssign::BCvt:
2978       Arg = DAG.getBitcast(RegVT, Arg);
2979       break;
2980     case CCValAssign::Indirect: {
2981       // Store the argument.
2982       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2983       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2984       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2985                            MachinePointerInfo::getFixedStack(FI),
2986                            false, false, 0);
2987       Arg = SpillSlot;
2988       break;
2989     }
2990     }
2991
2992     if (VA.isRegLoc()) {
2993       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2994       if (isVarArg && IsWin64) {
2995         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2996         // shadow reg if callee is a varargs function.
2997         unsigned ShadowReg = 0;
2998         switch (VA.getLocReg()) {
2999         case X86::XMM0: ShadowReg = X86::RCX; break;
3000         case X86::XMM1: ShadowReg = X86::RDX; break;
3001         case X86::XMM2: ShadowReg = X86::R8; break;
3002         case X86::XMM3: ShadowReg = X86::R9; break;
3003         }
3004         if (ShadowReg)
3005           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3006       }
3007     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3008       assert(VA.isMemLoc());
3009       if (!StackPtr.getNode())
3010         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3011                                       getPointerTy());
3012       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3013                                              dl, DAG, VA, Flags));
3014     }
3015   }
3016
3017   if (!MemOpChains.empty())
3018     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3019
3020   if (Subtarget->isPICStyleGOT()) {
3021     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3022     // GOT pointer.
3023     if (!isTailCall) {
3024       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
3025                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
3026     } else {
3027       // If we are tail calling and generating PIC/GOT style code load the
3028       // address of the callee into ECX. The value in ecx is used as target of
3029       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3030       // for tail calls on PIC/GOT architectures. Normally we would just put the
3031       // address of GOT into ebx and then call target@PLT. But for tail calls
3032       // ebx would be restored (since ebx is callee saved) before jumping to the
3033       // target@PLT.
3034
3035       // Note: The actual moving to ECX is done further down.
3036       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3037       if (G && !G->getGlobal()->hasLocalLinkage() &&
3038           G->getGlobal()->hasDefaultVisibility())
3039         Callee = LowerGlobalAddress(Callee, DAG);
3040       else if (isa<ExternalSymbolSDNode>(Callee))
3041         Callee = LowerExternalSymbol(Callee, DAG);
3042     }
3043   }
3044
3045   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3046     // From AMD64 ABI document:
3047     // For calls that may call functions that use varargs or stdargs
3048     // (prototype-less calls or calls to functions containing ellipsis (...) in
3049     // the declaration) %al is used as hidden argument to specify the number
3050     // of SSE registers used. The contents of %al do not need to match exactly
3051     // the number of registers, but must be an ubound on the number of SSE
3052     // registers used and is in the range 0 - 8 inclusive.
3053
3054     // Count the number of XMM registers allocated.
3055     static const MCPhysReg XMMArgRegs[] = {
3056       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3057       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3058     };
3059     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3060     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3061            && "SSE registers cannot be used when SSE is disabled");
3062
3063     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3064                                         DAG.getConstant(NumXMMRegs, dl,
3065                                                         MVT::i8)));
3066   }
3067
3068   if (isVarArg && IsMustTail) {
3069     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3070     for (const auto &F : Forwards) {
3071       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3072       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3073     }
3074   }
3075
3076   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3077   // don't need this because the eligibility check rejects calls that require
3078   // shuffling arguments passed in memory.
3079   if (!IsSibcall && isTailCall) {
3080     // Force all the incoming stack arguments to be loaded from the stack
3081     // before any new outgoing arguments are stored to the stack, because the
3082     // outgoing stack slots may alias the incoming argument stack slots, and
3083     // the alias isn't otherwise explicit. This is slightly more conservative
3084     // than necessary, because it means that each store effectively depends
3085     // on every argument instead of just those arguments it would clobber.
3086     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3087
3088     SmallVector<SDValue, 8> MemOpChains2;
3089     SDValue FIN;
3090     int FI = 0;
3091     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3092       CCValAssign &VA = ArgLocs[i];
3093       if (VA.isRegLoc())
3094         continue;
3095       assert(VA.isMemLoc());
3096       SDValue Arg = OutVals[i];
3097       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3098       // Skip inalloca arguments.  They don't require any work.
3099       if (Flags.isInAlloca())
3100         continue;
3101       // Create frame index.
3102       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3103       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3104       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3105       FIN = DAG.getFrameIndex(FI, getPointerTy());
3106
3107       if (Flags.isByVal()) {
3108         // Copy relative to framepointer.
3109         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3110         if (!StackPtr.getNode())
3111           StackPtr = DAG.getCopyFromReg(Chain, dl,
3112                                         RegInfo->getStackRegister(),
3113                                         getPointerTy());
3114         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3115
3116         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3117                                                          ArgChain,
3118                                                          Flags, DAG, dl));
3119       } else {
3120         // Store relative to framepointer.
3121         MemOpChains2.push_back(
3122           DAG.getStore(ArgChain, dl, Arg, FIN,
3123                        MachinePointerInfo::getFixedStack(FI),
3124                        false, false, 0));
3125       }
3126     }
3127
3128     if (!MemOpChains2.empty())
3129       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3130
3131     // Store the return address to the appropriate stack slot.
3132     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3133                                      getPointerTy(), RegInfo->getSlotSize(),
3134                                      FPDiff, dl);
3135   }
3136
3137   // Build a sequence of copy-to-reg nodes chained together with token chain
3138   // and flag operands which copy the outgoing args into registers.
3139   SDValue InFlag;
3140   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3141     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3142                              RegsToPass[i].second, InFlag);
3143     InFlag = Chain.getValue(1);
3144   }
3145
3146   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3147     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3148     // In the 64-bit large code model, we have to make all calls
3149     // through a register, since the call instruction's 32-bit
3150     // pc-relative offset may not be large enough to hold the whole
3151     // address.
3152   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3153     // If the callee is a GlobalAddress node (quite common, every direct call
3154     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3155     // it.
3156     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3157
3158     // We should use extra load for direct calls to dllimported functions in
3159     // non-JIT mode.
3160     const GlobalValue *GV = G->getGlobal();
3161     if (!GV->hasDLLImportStorageClass()) {
3162       unsigned char OpFlags = 0;
3163       bool ExtraLoad = false;
3164       unsigned WrapperKind = ISD::DELETED_NODE;
3165
3166       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3167       // external symbols most go through the PLT in PIC mode.  If the symbol
3168       // has hidden or protected visibility, or if it is static or local, then
3169       // we don't need to use the PLT - we can directly call it.
3170       if (Subtarget->isTargetELF() &&
3171           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3172           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3173         OpFlags = X86II::MO_PLT;
3174       } else if (Subtarget->isPICStyleStubAny() &&
3175                  !GV->isStrongDefinitionForLinker() &&
3176                  (!Subtarget->getTargetTriple().isMacOSX() ||
3177                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3178         // PC-relative references to external symbols should go through $stub,
3179         // unless we're building with the leopard linker or later, which
3180         // automatically synthesizes these stubs.
3181         OpFlags = X86II::MO_DARWIN_STUB;
3182       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3183                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3184         // If the function is marked as non-lazy, generate an indirect call
3185         // which loads from the GOT directly. This avoids runtime overhead
3186         // at the cost of eager binding (and one extra byte of encoding).
3187         OpFlags = X86II::MO_GOTPCREL;
3188         WrapperKind = X86ISD::WrapperRIP;
3189         ExtraLoad = true;
3190       }
3191
3192       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3193                                           G->getOffset(), OpFlags);
3194
3195       // Add a wrapper if needed.
3196       if (WrapperKind != ISD::DELETED_NODE)
3197         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3198       // Add extra indirection if needed.
3199       if (ExtraLoad)
3200         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3201                              MachinePointerInfo::getGOT(),
3202                              false, false, false, 0);
3203     }
3204   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3205     unsigned char OpFlags = 0;
3206
3207     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3208     // external symbols should go through the PLT.
3209     if (Subtarget->isTargetELF() &&
3210         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3211       OpFlags = X86II::MO_PLT;
3212     } else if (Subtarget->isPICStyleStubAny() &&
3213                (!Subtarget->getTargetTriple().isMacOSX() ||
3214                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3215       // PC-relative references to external symbols should go through $stub,
3216       // unless we're building with the leopard linker or later, which
3217       // automatically synthesizes these stubs.
3218       OpFlags = X86II::MO_DARWIN_STUB;
3219     }
3220
3221     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3222                                          OpFlags);
3223   } else if (Subtarget->isTarget64BitILP32() &&
3224              Callee->getValueType(0) == MVT::i32) {
3225     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3226     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3227   }
3228
3229   // Returns a chain & a flag for retval copy to use.
3230   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3231   SmallVector<SDValue, 8> Ops;
3232
3233   if (!IsSibcall && isTailCall) {
3234     Chain = DAG.getCALLSEQ_END(Chain,
3235                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3236                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3237     InFlag = Chain.getValue(1);
3238   }
3239
3240   Ops.push_back(Chain);
3241   Ops.push_back(Callee);
3242
3243   if (isTailCall)
3244     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3245
3246   // Add argument registers to the end of the list so that they are known live
3247   // into the call.
3248   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3249     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3250                                   RegsToPass[i].second.getValueType()));
3251
3252   // Add a register mask operand representing the call-preserved registers.
3253   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3254   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3255   assert(Mask && "Missing call preserved mask for calling convention");
3256   Ops.push_back(DAG.getRegisterMask(Mask));
3257
3258   if (InFlag.getNode())
3259     Ops.push_back(InFlag);
3260
3261   if (isTailCall) {
3262     // We used to do:
3263     //// If this is the first return lowered for this function, add the regs
3264     //// to the liveout set for the function.
3265     // This isn't right, although it's probably harmless on x86; liveouts
3266     // should be computed from returns not tail calls.  Consider a void
3267     // function making a tail call to a function returning int.
3268     MF.getFrameInfo()->setHasTailCall();
3269     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3270   }
3271
3272   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3273   InFlag = Chain.getValue(1);
3274
3275   // Create the CALLSEQ_END node.
3276   unsigned NumBytesForCalleeToPop;
3277   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3278                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3279     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3280   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3281            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3282            SR == StackStructReturn)
3283     // If this is a call to a struct-return function, the callee
3284     // pops the hidden struct pointer, so we have to push it back.
3285     // This is common for Darwin/X86, Linux & Mingw32 targets.
3286     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3287     NumBytesForCalleeToPop = 4;
3288   else
3289     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3290
3291   // Returns a flag for retval copy to use.
3292   if (!IsSibcall) {
3293     Chain = DAG.getCALLSEQ_END(Chain,
3294                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3295                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3296                                                      true),
3297                                InFlag, dl);
3298     InFlag = Chain.getValue(1);
3299   }
3300
3301   // Handle result values, copying them out of physregs into vregs that we
3302   // return.
3303   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3304                          Ins, dl, DAG, InVals);
3305 }
3306
3307 //===----------------------------------------------------------------------===//
3308 //                Fast Calling Convention (tail call) implementation
3309 //===----------------------------------------------------------------------===//
3310
3311 //  Like std call, callee cleans arguments, convention except that ECX is
3312 //  reserved for storing the tail called function address. Only 2 registers are
3313 //  free for argument passing (inreg). Tail call optimization is performed
3314 //  provided:
3315 //                * tailcallopt is enabled
3316 //                * caller/callee are fastcc
3317 //  On X86_64 architecture with GOT-style position independent code only local
3318 //  (within module) calls are supported at the moment.
3319 //  To keep the stack aligned according to platform abi the function
3320 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3321 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3322 //  If a tail called function callee has more arguments than the caller the
3323 //  caller needs to make sure that there is room to move the RETADDR to. This is
3324 //  achieved by reserving an area the size of the argument delta right after the
3325 //  original RETADDR, but before the saved framepointer or the spilled registers
3326 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3327 //  stack layout:
3328 //    arg1
3329 //    arg2
3330 //    RETADDR
3331 //    [ new RETADDR
3332 //      move area ]
3333 //    (possible EBP)
3334 //    ESI
3335 //    EDI
3336 //    local1 ..
3337
3338 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3339 /// for a 16 byte align requirement.
3340 unsigned
3341 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3342                                                SelectionDAG& DAG) const {
3343   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3344   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3345   unsigned StackAlignment = TFI.getStackAlignment();
3346   uint64_t AlignMask = StackAlignment - 1;
3347   int64_t Offset = StackSize;
3348   unsigned SlotSize = RegInfo->getSlotSize();
3349   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3350     // Number smaller than 12 so just add the difference.
3351     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3352   } else {
3353     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3354     Offset = ((~AlignMask) & Offset) + StackAlignment +
3355       (StackAlignment-SlotSize);
3356   }
3357   return Offset;
3358 }
3359
3360 /// MatchingStackOffset - Return true if the given stack call argument is
3361 /// already available in the same position (relatively) of the caller's
3362 /// incoming argument stack.
3363 static
3364 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3365                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3366                          const X86InstrInfo *TII) {
3367   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3368   int FI = INT_MAX;
3369   if (Arg.getOpcode() == ISD::CopyFromReg) {
3370     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3371     if (!TargetRegisterInfo::isVirtualRegister(VR))
3372       return false;
3373     MachineInstr *Def = MRI->getVRegDef(VR);
3374     if (!Def)
3375       return false;
3376     if (!Flags.isByVal()) {
3377       if (!TII->isLoadFromStackSlot(Def, FI))
3378         return false;
3379     } else {
3380       unsigned Opcode = Def->getOpcode();
3381       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3382            Opcode == X86::LEA64_32r) &&
3383           Def->getOperand(1).isFI()) {
3384         FI = Def->getOperand(1).getIndex();
3385         Bytes = Flags.getByValSize();
3386       } else
3387         return false;
3388     }
3389   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3390     if (Flags.isByVal())
3391       // ByVal argument is passed in as a pointer but it's now being
3392       // dereferenced. e.g.
3393       // define @foo(%struct.X* %A) {
3394       //   tail call @bar(%struct.X* byval %A)
3395       // }
3396       return false;
3397     SDValue Ptr = Ld->getBasePtr();
3398     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3399     if (!FINode)
3400       return false;
3401     FI = FINode->getIndex();
3402   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3403     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3404     FI = FINode->getIndex();
3405     Bytes = Flags.getByValSize();
3406   } else
3407     return false;
3408
3409   assert(FI != INT_MAX);
3410   if (!MFI->isFixedObjectIndex(FI))
3411     return false;
3412   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3413 }
3414
3415 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3416 /// for tail call optimization. Targets which want to do tail call
3417 /// optimization should implement this function.
3418 bool
3419 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3420                                                      CallingConv::ID CalleeCC,
3421                                                      bool isVarArg,
3422                                                      bool isCalleeStructRet,
3423                                                      bool isCallerStructRet,
3424                                                      Type *RetTy,
3425                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3426                                     const SmallVectorImpl<SDValue> &OutVals,
3427                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3428                                                      SelectionDAG &DAG) const {
3429   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3430     return false;
3431
3432   // If -tailcallopt is specified, make fastcc functions tail-callable.
3433   const MachineFunction &MF = DAG.getMachineFunction();
3434   const Function *CallerF = MF.getFunction();
3435
3436   // If the function return type is x86_fp80 and the callee return type is not,
3437   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3438   // perform a tailcall optimization here.
3439   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3440     return false;
3441
3442   CallingConv::ID CallerCC = CallerF->getCallingConv();
3443   bool CCMatch = CallerCC == CalleeCC;
3444   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3445   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3446
3447   // Win64 functions have extra shadow space for argument homing. Don't do the
3448   // sibcall if the caller and callee have mismatched expectations for this
3449   // space.
3450   if (IsCalleeWin64 != IsCallerWin64)
3451     return false;
3452
3453   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3454     if (IsTailCallConvention(CalleeCC) && CCMatch)
3455       return true;
3456     return false;
3457   }
3458
3459   // Look for obvious safe cases to perform tail call optimization that do not
3460   // require ABI changes. This is what gcc calls sibcall.
3461
3462   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3463   // emit a special epilogue.
3464   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3465   if (RegInfo->needsStackRealignment(MF))
3466     return false;
3467
3468   // Also avoid sibcall optimization if either caller or callee uses struct
3469   // return semantics.
3470   if (isCalleeStructRet || isCallerStructRet)
3471     return false;
3472
3473   // An stdcall/thiscall caller is expected to clean up its arguments; the
3474   // callee isn't going to do that.
3475   // FIXME: this is more restrictive than needed. We could produce a tailcall
3476   // when the stack adjustment matches. For example, with a thiscall that takes
3477   // only one argument.
3478   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3479                    CallerCC == CallingConv::X86_ThisCall))
3480     return false;
3481
3482   // Do not sibcall optimize vararg calls unless all arguments are passed via
3483   // registers.
3484   if (isVarArg && !Outs.empty()) {
3485
3486     // Optimizing for varargs on Win64 is unlikely to be safe without
3487     // additional testing.
3488     if (IsCalleeWin64 || IsCallerWin64)
3489       return false;
3490
3491     SmallVector<CCValAssign, 16> ArgLocs;
3492     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3493                    *DAG.getContext());
3494
3495     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3496     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3497       if (!ArgLocs[i].isRegLoc())
3498         return false;
3499   }
3500
3501   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3502   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3503   // this into a sibcall.
3504   bool Unused = false;
3505   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3506     if (!Ins[i].Used) {
3507       Unused = true;
3508       break;
3509     }
3510   }
3511   if (Unused) {
3512     SmallVector<CCValAssign, 16> RVLocs;
3513     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3514                    *DAG.getContext());
3515     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3516     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3517       CCValAssign &VA = RVLocs[i];
3518       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3519         return false;
3520     }
3521   }
3522
3523   // If the calling conventions do not match, then we'd better make sure the
3524   // results are returned in the same way as what the caller expects.
3525   if (!CCMatch) {
3526     SmallVector<CCValAssign, 16> RVLocs1;
3527     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3528                     *DAG.getContext());
3529     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3530
3531     SmallVector<CCValAssign, 16> RVLocs2;
3532     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3533                     *DAG.getContext());
3534     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3535
3536     if (RVLocs1.size() != RVLocs2.size())
3537       return false;
3538     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3539       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3540         return false;
3541       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3542         return false;
3543       if (RVLocs1[i].isRegLoc()) {
3544         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3545           return false;
3546       } else {
3547         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3548           return false;
3549       }
3550     }
3551   }
3552
3553   // If the callee takes no arguments then go on to check the results of the
3554   // call.
3555   if (!Outs.empty()) {
3556     // Check if stack adjustment is needed. For now, do not do this if any
3557     // argument is passed on the stack.
3558     SmallVector<CCValAssign, 16> ArgLocs;
3559     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3560                    *DAG.getContext());
3561
3562     // Allocate shadow area for Win64
3563     if (IsCalleeWin64)
3564       CCInfo.AllocateStack(32, 8);
3565
3566     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3567     if (CCInfo.getNextStackOffset()) {
3568       MachineFunction &MF = DAG.getMachineFunction();
3569       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3570         return false;
3571
3572       // Check if the arguments are already laid out in the right way as
3573       // the caller's fixed stack objects.
3574       MachineFrameInfo *MFI = MF.getFrameInfo();
3575       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3576       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3577       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3578         CCValAssign &VA = ArgLocs[i];
3579         SDValue Arg = OutVals[i];
3580         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3581         if (VA.getLocInfo() == CCValAssign::Indirect)
3582           return false;
3583         if (!VA.isRegLoc()) {
3584           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3585                                    MFI, MRI, TII))
3586             return false;
3587         }
3588       }
3589     }
3590
3591     // If the tailcall address may be in a register, then make sure it's
3592     // possible to register allocate for it. In 32-bit, the call address can
3593     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3594     // callee-saved registers are restored. These happen to be the same
3595     // registers used to pass 'inreg' arguments so watch out for those.
3596     if (!Subtarget->is64Bit() &&
3597         ((!isa<GlobalAddressSDNode>(Callee) &&
3598           !isa<ExternalSymbolSDNode>(Callee)) ||
3599          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3600       unsigned NumInRegs = 0;
3601       // In PIC we need an extra register to formulate the address computation
3602       // for the callee.
3603       unsigned MaxInRegs =
3604         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3605
3606       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3607         CCValAssign &VA = ArgLocs[i];
3608         if (!VA.isRegLoc())
3609           continue;
3610         unsigned Reg = VA.getLocReg();
3611         switch (Reg) {
3612         default: break;
3613         case X86::EAX: case X86::EDX: case X86::ECX:
3614           if (++NumInRegs == MaxInRegs)
3615             return false;
3616           break;
3617         }
3618       }
3619     }
3620   }
3621
3622   return true;
3623 }
3624
3625 FastISel *
3626 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3627                                   const TargetLibraryInfo *libInfo) const {
3628   return X86::createFastISel(funcInfo, libInfo);
3629 }
3630
3631 //===----------------------------------------------------------------------===//
3632 //                           Other Lowering Hooks
3633 //===----------------------------------------------------------------------===//
3634
3635 static bool MayFoldLoad(SDValue Op) {
3636   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3637 }
3638
3639 static bool MayFoldIntoStore(SDValue Op) {
3640   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3641 }
3642
3643 static bool isTargetShuffle(unsigned Opcode) {
3644   switch(Opcode) {
3645   default: return false;
3646   case X86ISD::BLENDI:
3647   case X86ISD::PSHUFB:
3648   case X86ISD::PSHUFD:
3649   case X86ISD::PSHUFHW:
3650   case X86ISD::PSHUFLW:
3651   case X86ISD::SHUFP:
3652   case X86ISD::PALIGNR:
3653   case X86ISD::MOVLHPS:
3654   case X86ISD::MOVLHPD:
3655   case X86ISD::MOVHLPS:
3656   case X86ISD::MOVLPS:
3657   case X86ISD::MOVLPD:
3658   case X86ISD::MOVSHDUP:
3659   case X86ISD::MOVSLDUP:
3660   case X86ISD::MOVDDUP:
3661   case X86ISD::MOVSS:
3662   case X86ISD::MOVSD:
3663   case X86ISD::UNPCKL:
3664   case X86ISD::UNPCKH:
3665   case X86ISD::VPERMILPI:
3666   case X86ISD::VPERM2X128:
3667   case X86ISD::VPERMI:
3668     return true;
3669   }
3670 }
3671
3672 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3673                                     SDValue V1, unsigned TargetMask,
3674                                     SelectionDAG &DAG) {
3675   switch(Opc) {
3676   default: llvm_unreachable("Unknown x86 shuffle node");
3677   case X86ISD::PSHUFD:
3678   case X86ISD::PSHUFHW:
3679   case X86ISD::PSHUFLW:
3680   case X86ISD::VPERMILPI:
3681   case X86ISD::VPERMI:
3682     return DAG.getNode(Opc, dl, VT, V1,
3683                        DAG.getConstant(TargetMask, dl, MVT::i8));
3684   }
3685 }
3686
3687 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3688                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3689   switch(Opc) {
3690   default: llvm_unreachable("Unknown x86 shuffle node");
3691   case X86ISD::MOVLHPS:
3692   case X86ISD::MOVLHPD:
3693   case X86ISD::MOVHLPS:
3694   case X86ISD::MOVLPS:
3695   case X86ISD::MOVLPD:
3696   case X86ISD::MOVSS:
3697   case X86ISD::MOVSD:
3698   case X86ISD::UNPCKL:
3699   case X86ISD::UNPCKH:
3700     return DAG.getNode(Opc, dl, VT, V1, V2);
3701   }
3702 }
3703
3704 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3705   MachineFunction &MF = DAG.getMachineFunction();
3706   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3707   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3708   int ReturnAddrIndex = FuncInfo->getRAIndex();
3709
3710   if (ReturnAddrIndex == 0) {
3711     // Set up a frame object for the return address.
3712     unsigned SlotSize = RegInfo->getSlotSize();
3713     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3714                                                            -(int64_t)SlotSize,
3715                                                            false);
3716     FuncInfo->setRAIndex(ReturnAddrIndex);
3717   }
3718
3719   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3720 }
3721
3722 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3723                                        bool hasSymbolicDisplacement) {
3724   // Offset should fit into 32 bit immediate field.
3725   if (!isInt<32>(Offset))
3726     return false;
3727
3728   // If we don't have a symbolic displacement - we don't have any extra
3729   // restrictions.
3730   if (!hasSymbolicDisplacement)
3731     return true;
3732
3733   // FIXME: Some tweaks might be needed for medium code model.
3734   if (M != CodeModel::Small && M != CodeModel::Kernel)
3735     return false;
3736
3737   // For small code model we assume that latest object is 16MB before end of 31
3738   // bits boundary. We may also accept pretty large negative constants knowing
3739   // that all objects are in the positive half of address space.
3740   if (M == CodeModel::Small && Offset < 16*1024*1024)
3741     return true;
3742
3743   // For kernel code model we know that all object resist in the negative half
3744   // of 32bits address space. We may not accept negative offsets, since they may
3745   // be just off and we may accept pretty large positive ones.
3746   if (M == CodeModel::Kernel && Offset >= 0)
3747     return true;
3748
3749   return false;
3750 }
3751
3752 /// isCalleePop - Determines whether the callee is required to pop its
3753 /// own arguments. Callee pop is necessary to support tail calls.
3754 bool X86::isCalleePop(CallingConv::ID CallingConv,
3755                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3756   switch (CallingConv) {
3757   default:
3758     return false;
3759   case CallingConv::X86_StdCall:
3760   case CallingConv::X86_FastCall:
3761   case CallingConv::X86_ThisCall:
3762     return !is64Bit;
3763   case CallingConv::Fast:
3764   case CallingConv::GHC:
3765   case CallingConv::HiPE:
3766     if (IsVarArg)
3767       return false;
3768     return TailCallOpt;
3769   }
3770 }
3771
3772 /// \brief Return true if the condition is an unsigned comparison operation.
3773 static bool isX86CCUnsigned(unsigned X86CC) {
3774   switch (X86CC) {
3775   default: llvm_unreachable("Invalid integer condition!");
3776   case X86::COND_E:     return true;
3777   case X86::COND_G:     return false;
3778   case X86::COND_GE:    return false;
3779   case X86::COND_L:     return false;
3780   case X86::COND_LE:    return false;
3781   case X86::COND_NE:    return true;
3782   case X86::COND_B:     return true;
3783   case X86::COND_A:     return true;
3784   case X86::COND_BE:    return true;
3785   case X86::COND_AE:    return true;
3786   }
3787   llvm_unreachable("covered switch fell through?!");
3788 }
3789
3790 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3791 /// specific condition code, returning the condition code and the LHS/RHS of the
3792 /// comparison to make.
3793 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3794                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3795   if (!isFP) {
3796     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3797       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3798         // X > -1   -> X == 0, jump !sign.
3799         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3800         return X86::COND_NS;
3801       }
3802       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3803         // X < 0   -> X == 0, jump on sign.
3804         return X86::COND_S;
3805       }
3806       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3807         // X < 1   -> X <= 0
3808         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3809         return X86::COND_LE;
3810       }
3811     }
3812
3813     switch (SetCCOpcode) {
3814     default: llvm_unreachable("Invalid integer condition!");
3815     case ISD::SETEQ:  return X86::COND_E;
3816     case ISD::SETGT:  return X86::COND_G;
3817     case ISD::SETGE:  return X86::COND_GE;
3818     case ISD::SETLT:  return X86::COND_L;
3819     case ISD::SETLE:  return X86::COND_LE;
3820     case ISD::SETNE:  return X86::COND_NE;
3821     case ISD::SETULT: return X86::COND_B;
3822     case ISD::SETUGT: return X86::COND_A;
3823     case ISD::SETULE: return X86::COND_BE;
3824     case ISD::SETUGE: return X86::COND_AE;
3825     }
3826   }
3827
3828   // First determine if it is required or is profitable to flip the operands.
3829
3830   // If LHS is a foldable load, but RHS is not, flip the condition.
3831   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3832       !ISD::isNON_EXTLoad(RHS.getNode())) {
3833     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3834     std::swap(LHS, RHS);
3835   }
3836
3837   switch (SetCCOpcode) {
3838   default: break;
3839   case ISD::SETOLT:
3840   case ISD::SETOLE:
3841   case ISD::SETUGT:
3842   case ISD::SETUGE:
3843     std::swap(LHS, RHS);
3844     break;
3845   }
3846
3847   // On a floating point condition, the flags are set as follows:
3848   // ZF  PF  CF   op
3849   //  0 | 0 | 0 | X > Y
3850   //  0 | 0 | 1 | X < Y
3851   //  1 | 0 | 0 | X == Y
3852   //  1 | 1 | 1 | unordered
3853   switch (SetCCOpcode) {
3854   default: llvm_unreachable("Condcode should be pre-legalized away");
3855   case ISD::SETUEQ:
3856   case ISD::SETEQ:   return X86::COND_E;
3857   case ISD::SETOLT:              // flipped
3858   case ISD::SETOGT:
3859   case ISD::SETGT:   return X86::COND_A;
3860   case ISD::SETOLE:              // flipped
3861   case ISD::SETOGE:
3862   case ISD::SETGE:   return X86::COND_AE;
3863   case ISD::SETUGT:              // flipped
3864   case ISD::SETULT:
3865   case ISD::SETLT:   return X86::COND_B;
3866   case ISD::SETUGE:              // flipped
3867   case ISD::SETULE:
3868   case ISD::SETLE:   return X86::COND_BE;
3869   case ISD::SETONE:
3870   case ISD::SETNE:   return X86::COND_NE;
3871   case ISD::SETUO:   return X86::COND_P;
3872   case ISD::SETO:    return X86::COND_NP;
3873   case ISD::SETOEQ:
3874   case ISD::SETUNE:  return X86::COND_INVALID;
3875   }
3876 }
3877
3878 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3879 /// code. Current x86 isa includes the following FP cmov instructions:
3880 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3881 static bool hasFPCMov(unsigned X86CC) {
3882   switch (X86CC) {
3883   default:
3884     return false;
3885   case X86::COND_B:
3886   case X86::COND_BE:
3887   case X86::COND_E:
3888   case X86::COND_P:
3889   case X86::COND_A:
3890   case X86::COND_AE:
3891   case X86::COND_NE:
3892   case X86::COND_NP:
3893     return true;
3894   }
3895 }
3896
3897 /// isFPImmLegal - Returns true if the target can instruction select the
3898 /// specified FP immediate natively. If false, the legalizer will
3899 /// materialize the FP immediate as a load from a constant pool.
3900 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3901   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3902     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3903       return true;
3904   }
3905   return false;
3906 }
3907
3908 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3909                                               ISD::LoadExtType ExtTy,
3910                                               EVT NewVT) const {
3911   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3912   // relocation target a movq or addq instruction: don't let the load shrink.
3913   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3914   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3915     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3916       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3917   return true;
3918 }
3919
3920 /// \brief Returns true if it is beneficial to convert a load of a constant
3921 /// to just the constant itself.
3922 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3923                                                           Type *Ty) const {
3924   assert(Ty->isIntegerTy());
3925
3926   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3927   if (BitSize == 0 || BitSize > 64)
3928     return false;
3929   return true;
3930 }
3931
3932 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3933                                                 unsigned Index) const {
3934   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3935     return false;
3936
3937   return (Index == 0 || Index == ResVT.getVectorNumElements());
3938 }
3939
3940 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3941   // Speculate cttz only if we can directly use TZCNT.
3942   return Subtarget->hasBMI();
3943 }
3944
3945 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3946   // Speculate ctlz only if we can directly use LZCNT.
3947   return Subtarget->hasLZCNT();
3948 }
3949
3950 /// isUndefInRange - Return true if every element in Mask, beginning
3951 /// from position Pos and ending in Pos+Size is undef.
3952 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3953   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
3954     if (0 <= Mask[i])
3955       return false;
3956   return true;
3957 }
3958
3959 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3960 /// the specified range (L, H].
3961 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3962   return (Val < 0) || (Val >= Low && Val < Hi);
3963 }
3964
3965 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3966 /// specified value.
3967 static bool isUndefOrEqual(int Val, int CmpVal) {
3968   return (Val < 0 || Val == CmpVal);
3969 }
3970
3971 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3972 /// from position Pos and ending in Pos+Size, falls within the specified
3973 /// sequential range (Low, Low+Size]. or is undef.
3974 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3975                                        unsigned Pos, unsigned Size, int Low) {
3976   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3977     if (!isUndefOrEqual(Mask[i], Low))
3978       return false;
3979   return true;
3980 }
3981
3982 /// isVEXTRACTIndex - Return true if the specified
3983 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3984 /// suitable for instruction that extract 128 or 256 bit vectors
3985 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3986   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3987   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3988     return false;
3989
3990   // The index should be aligned on a vecWidth-bit boundary.
3991   uint64_t Index =
3992     cast<ConstantSDNode>(N->getOperand(1).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 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4002 /// operand specifies a subvector insert that is suitable for input to
4003 /// insertion of 128 or 256-bit subvectors
4004 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4005   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4006   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4007     return false;
4008   // The index should be aligned on a vecWidth-bit boundary.
4009   uint64_t Index =
4010     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4011
4012   MVT VT = N->getSimpleValueType(0);
4013   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4014   bool Result = (Index * ElSize) % vecWidth == 0;
4015
4016   return Result;
4017 }
4018
4019 bool X86::isVINSERT128Index(SDNode *N) {
4020   return isVINSERTIndex(N, 128);
4021 }
4022
4023 bool X86::isVINSERT256Index(SDNode *N) {
4024   return isVINSERTIndex(N, 256);
4025 }
4026
4027 bool X86::isVEXTRACT128Index(SDNode *N) {
4028   return isVEXTRACTIndex(N, 128);
4029 }
4030
4031 bool X86::isVEXTRACT256Index(SDNode *N) {
4032   return isVEXTRACTIndex(N, 256);
4033 }
4034
4035 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4036   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4037   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4038     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4039
4040   uint64_t Index =
4041     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4042
4043   MVT VecVT = N->getOperand(0).getSimpleValueType();
4044   MVT ElVT = VecVT.getVectorElementType();
4045
4046   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4047   return Index / NumElemsPerChunk;
4048 }
4049
4050 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4051   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4052   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4053     llvm_unreachable("Illegal insert subvector for VINSERT");
4054
4055   uint64_t Index =
4056     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4057
4058   MVT VecVT = N->getSimpleValueType(0);
4059   MVT ElVT = VecVT.getVectorElementType();
4060
4061   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4062   return Index / NumElemsPerChunk;
4063 }
4064
4065 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4066 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4067 /// and VINSERTI128 instructions.
4068 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4069   return getExtractVEXTRACTImmediate(N, 128);
4070 }
4071
4072 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4073 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4074 /// and VINSERTI64x4 instructions.
4075 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4076   return getExtractVEXTRACTImmediate(N, 256);
4077 }
4078
4079 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4080 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4081 /// and VINSERTI128 instructions.
4082 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4083   return getInsertVINSERTImmediate(N, 128);
4084 }
4085
4086 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4087 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4088 /// and VINSERTI64x4 instructions.
4089 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4090   return getInsertVINSERTImmediate(N, 256);
4091 }
4092
4093 /// isZero - Returns true if Elt is a constant integer zero
4094 static bool isZero(SDValue V) {
4095   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4096   return C && C->isNullValue();
4097 }
4098
4099 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4100 /// constant +0.0.
4101 bool X86::isZeroNode(SDValue Elt) {
4102   if (isZero(Elt))
4103     return true;
4104   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4105     return CFP->getValueAPF().isPosZero();
4106   return false;
4107 }
4108
4109 /// getZeroVector - Returns a vector of specified type with all zero elements.
4110 ///
4111 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4112                              SelectionDAG &DAG, SDLoc dl) {
4113   assert(VT.isVector() && "Expected a vector type");
4114
4115   // Always build SSE zero vectors as <4 x i32> bitcasted
4116   // to their dest type. This ensures they get CSE'd.
4117   SDValue Vec;
4118   if (VT.is128BitVector()) {  // SSE
4119     if (Subtarget->hasSSE2()) {  // SSE2
4120       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4121       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4122     } else { // SSE1
4123       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4124       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4125     }
4126   } else if (VT.is256BitVector()) { // AVX
4127     if (Subtarget->hasInt256()) { // AVX2
4128       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4129       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4130       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4131     } else {
4132       // 256-bit logic and arithmetic instructions in AVX are all
4133       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4134       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4135       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4136       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4137     }
4138   } else if (VT.is512BitVector()) { // AVX-512
4139       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4140       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4141                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4142       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4143   } else if (VT.getScalarType() == MVT::i1) {
4144
4145     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4146             && "Unexpected vector type");
4147     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4148             && "Unexpected vector type");
4149     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4150     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4151     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4152   } else
4153     llvm_unreachable("Unexpected vector type");
4154
4155   return DAG.getBitcast(VT, Vec);
4156 }
4157
4158 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4159                                 SelectionDAG &DAG, SDLoc dl,
4160                                 unsigned vectorWidth) {
4161   assert((vectorWidth == 128 || vectorWidth == 256) &&
4162          "Unsupported vector width");
4163   EVT VT = Vec.getValueType();
4164   EVT ElVT = VT.getVectorElementType();
4165   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4166   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4167                                   VT.getVectorNumElements()/Factor);
4168
4169   // Extract from UNDEF is UNDEF.
4170   if (Vec.getOpcode() == ISD::UNDEF)
4171     return DAG.getUNDEF(ResultVT);
4172
4173   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4174   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4175
4176   // This is the index of the first element of the vectorWidth-bit chunk
4177   // we want.
4178   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4179                                * ElemsPerChunk);
4180
4181   // If the input is a buildvector just emit a smaller one.
4182   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4183     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4184                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4185                                     ElemsPerChunk));
4186
4187   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4188   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4189 }
4190
4191 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4192 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4193 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4194 /// instructions or a simple subregister reference. Idx is an index in the
4195 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4196 /// lowering EXTRACT_VECTOR_ELT operations easier.
4197 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4198                                    SelectionDAG &DAG, SDLoc dl) {
4199   assert((Vec.getValueType().is256BitVector() ||
4200           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4201   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4202 }
4203
4204 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4205 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4206                                    SelectionDAG &DAG, SDLoc dl) {
4207   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4208   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4209 }
4210
4211 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4212                                unsigned IdxVal, SelectionDAG &DAG,
4213                                SDLoc dl, unsigned vectorWidth) {
4214   assert((vectorWidth == 128 || vectorWidth == 256) &&
4215          "Unsupported vector width");
4216   // Inserting UNDEF is Result
4217   if (Vec.getOpcode() == ISD::UNDEF)
4218     return Result;
4219   EVT VT = Vec.getValueType();
4220   EVT ElVT = VT.getVectorElementType();
4221   EVT ResultVT = Result.getValueType();
4222
4223   // Insert the relevant vectorWidth bits.
4224   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4225
4226   // This is the index of the first element of the vectorWidth-bit chunk
4227   // we want.
4228   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4229                                * ElemsPerChunk);
4230
4231   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4232   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4233 }
4234
4235 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4236 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4237 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4238 /// simple superregister reference.  Idx is an index in the 128 bits
4239 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4240 /// lowering INSERT_VECTOR_ELT operations easier.
4241 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4242                                   SelectionDAG &DAG, SDLoc dl) {
4243   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4244
4245   // For insertion into the zero index (low half) of a 256-bit vector, it is
4246   // more efficient to generate a blend with immediate instead of an insert*128.
4247   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4248   // extend the subvector to the size of the result vector. Make sure that
4249   // we are not recursing on that node by checking for undef here.
4250   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4251       Result.getOpcode() != ISD::UNDEF) {
4252     EVT ResultVT = Result.getValueType();
4253     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4254     SDValue Undef = DAG.getUNDEF(ResultVT);
4255     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4256                                  Vec, ZeroIndex);
4257
4258     // The blend instruction, and therefore its mask, depend on the data type.
4259     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4260     if (ScalarType.isFloatingPoint()) {
4261       // Choose either vblendps (float) or vblendpd (double).
4262       unsigned ScalarSize = ScalarType.getSizeInBits();
4263       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4264       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4265       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4266       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4267     }
4268
4269     const X86Subtarget &Subtarget =
4270     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4271
4272     // AVX2 is needed for 256-bit integer blend support.
4273     // Integers must be cast to 32-bit because there is only vpblendd;
4274     // vpblendw can't be used for this because it has a handicapped mask.
4275
4276     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4277     // is still more efficient than using the wrong domain vinsertf128 that
4278     // will be created by InsertSubVector().
4279     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4280
4281     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4282     Vec256 = DAG.getBitcast(CastVT, Vec256);
4283     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4284     return DAG.getBitcast(ResultVT, Vec256);
4285   }
4286
4287   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4288 }
4289
4290 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4291                                   SelectionDAG &DAG, SDLoc dl) {
4292   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4293   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4294 }
4295
4296 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4297 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4298 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4299 /// large BUILD_VECTORS.
4300 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4301                                    unsigned NumElems, SelectionDAG &DAG,
4302                                    SDLoc dl) {
4303   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4304   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4305 }
4306
4307 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4308                                    unsigned NumElems, SelectionDAG &DAG,
4309                                    SDLoc dl) {
4310   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4311   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4312 }
4313
4314 /// getOnesVector - Returns a vector of specified type with all bits set.
4315 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4316 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4317 /// Then bitcast to their original type, ensuring they get CSE'd.
4318 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4319                              SDLoc dl) {
4320   assert(VT.isVector() && "Expected a vector type");
4321
4322   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4323   SDValue Vec;
4324   if (VT.is256BitVector()) {
4325     if (HasInt256) { // AVX2
4326       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4327       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4328     } else { // AVX
4329       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4330       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4331     }
4332   } else if (VT.is128BitVector()) {
4333     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4334   } else
4335     llvm_unreachable("Unexpected vector type");
4336
4337   return DAG.getBitcast(VT, Vec);
4338 }
4339
4340 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4341 /// operation of specified width.
4342 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4343                        SDValue V2) {
4344   unsigned NumElems = VT.getVectorNumElements();
4345   SmallVector<int, 8> Mask;
4346   Mask.push_back(NumElems);
4347   for (unsigned i = 1; i != NumElems; ++i)
4348     Mask.push_back(i);
4349   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4350 }
4351
4352 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4353 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4354                           SDValue V2) {
4355   unsigned NumElems = VT.getVectorNumElements();
4356   SmallVector<int, 8> Mask;
4357   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4358     Mask.push_back(i);
4359     Mask.push_back(i + NumElems);
4360   }
4361   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4362 }
4363
4364 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4365 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4366                           SDValue V2) {
4367   unsigned NumElems = VT.getVectorNumElements();
4368   SmallVector<int, 8> Mask;
4369   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4370     Mask.push_back(i + Half);
4371     Mask.push_back(i + NumElems + Half);
4372   }
4373   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4374 }
4375
4376 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4377 /// vector of zero or undef vector.  This produces a shuffle where the low
4378 /// element of V2 is swizzled into the zero/undef vector, landing at element
4379 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4380 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4381                                            bool IsZero,
4382                                            const X86Subtarget *Subtarget,
4383                                            SelectionDAG &DAG) {
4384   MVT VT = V2.getSimpleValueType();
4385   SDValue V1 = IsZero
4386     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4387   unsigned NumElems = VT.getVectorNumElements();
4388   SmallVector<int, 16> MaskVec;
4389   for (unsigned i = 0; i != NumElems; ++i)
4390     // If this is the insertion idx, put the low elt of V2 here.
4391     MaskVec.push_back(i == Idx ? NumElems : i);
4392   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4393 }
4394
4395 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4396 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4397 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4398 /// shuffles which use a single input multiple times, and in those cases it will
4399 /// adjust the mask to only have indices within that single input.
4400 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4401 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4402                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4403   unsigned NumElems = VT.getVectorNumElements();
4404   SDValue ImmN;
4405
4406   IsUnary = false;
4407   bool IsFakeUnary = false;
4408   switch(N->getOpcode()) {
4409   case X86ISD::BLENDI:
4410     ImmN = N->getOperand(N->getNumOperands()-1);
4411     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4412     break;
4413   case X86ISD::SHUFP:
4414     ImmN = N->getOperand(N->getNumOperands()-1);
4415     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4416     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4417     break;
4418   case X86ISD::UNPCKH:
4419     DecodeUNPCKHMask(VT, Mask);
4420     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4421     break;
4422   case X86ISD::UNPCKL:
4423     DecodeUNPCKLMask(VT, Mask);
4424     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4425     break;
4426   case X86ISD::MOVHLPS:
4427     DecodeMOVHLPSMask(NumElems, Mask);
4428     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4429     break;
4430   case X86ISD::MOVLHPS:
4431     DecodeMOVLHPSMask(NumElems, Mask);
4432     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4433     break;
4434   case X86ISD::PALIGNR:
4435     ImmN = N->getOperand(N->getNumOperands()-1);
4436     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4437     break;
4438   case X86ISD::PSHUFD:
4439   case X86ISD::VPERMILPI:
4440     ImmN = N->getOperand(N->getNumOperands()-1);
4441     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4442     IsUnary = true;
4443     break;
4444   case X86ISD::PSHUFHW:
4445     ImmN = N->getOperand(N->getNumOperands()-1);
4446     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4447     IsUnary = true;
4448     break;
4449   case X86ISD::PSHUFLW:
4450     ImmN = N->getOperand(N->getNumOperands()-1);
4451     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4452     IsUnary = true;
4453     break;
4454   case X86ISD::PSHUFB: {
4455     IsUnary = true;
4456     SDValue MaskNode = N->getOperand(1);
4457     while (MaskNode->getOpcode() == ISD::BITCAST)
4458       MaskNode = MaskNode->getOperand(0);
4459
4460     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4461       // If we have a build-vector, then things are easy.
4462       EVT VT = MaskNode.getValueType();
4463       assert(VT.isVector() &&
4464              "Can't produce a non-vector with a build_vector!");
4465       if (!VT.isInteger())
4466         return false;
4467
4468       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4469
4470       SmallVector<uint64_t, 32> RawMask;
4471       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4472         SDValue Op = MaskNode->getOperand(i);
4473         if (Op->getOpcode() == ISD::UNDEF) {
4474           RawMask.push_back((uint64_t)SM_SentinelUndef);
4475           continue;
4476         }
4477         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4478         if (!CN)
4479           return false;
4480         APInt MaskElement = CN->getAPIntValue();
4481
4482         // We now have to decode the element which could be any integer size and
4483         // extract each byte of it.
4484         for (int j = 0; j < NumBytesPerElement; ++j) {
4485           // Note that this is x86 and so always little endian: the low byte is
4486           // the first byte of the mask.
4487           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4488           MaskElement = MaskElement.lshr(8);
4489         }
4490       }
4491       DecodePSHUFBMask(RawMask, Mask);
4492       break;
4493     }
4494
4495     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4496     if (!MaskLoad)
4497       return false;
4498
4499     SDValue Ptr = MaskLoad->getBasePtr();
4500     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4501         Ptr->getOpcode() == X86ISD::WrapperRIP)
4502       Ptr = Ptr->getOperand(0);
4503
4504     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4505     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4506       return false;
4507
4508     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4509       DecodePSHUFBMask(C, Mask);
4510       if (Mask.empty())
4511         return false;
4512       break;
4513     }
4514
4515     return false;
4516   }
4517   case X86ISD::VPERMI:
4518     ImmN = N->getOperand(N->getNumOperands()-1);
4519     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4520     IsUnary = true;
4521     break;
4522   case X86ISD::MOVSS:
4523   case X86ISD::MOVSD:
4524     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4525     break;
4526   case X86ISD::VPERM2X128:
4527     ImmN = N->getOperand(N->getNumOperands()-1);
4528     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4529     if (Mask.empty()) return false;
4530     // Mask only contains negative index if an element is zero.
4531     if (std::any_of(Mask.begin(), Mask.end(), 
4532                     [](int M){ return M == SM_SentinelZero; }))
4533       return false;
4534     break;
4535   case X86ISD::MOVSLDUP:
4536     DecodeMOVSLDUPMask(VT, Mask);
4537     IsUnary = true;
4538     break;
4539   case X86ISD::MOVSHDUP:
4540     DecodeMOVSHDUPMask(VT, Mask);
4541     IsUnary = true;
4542     break;
4543   case X86ISD::MOVDDUP:
4544     DecodeMOVDDUPMask(VT, Mask);
4545     IsUnary = true;
4546     break;
4547   case X86ISD::MOVLHPD:
4548   case X86ISD::MOVLPD:
4549   case X86ISD::MOVLPS:
4550     // Not yet implemented
4551     return false;
4552   default: llvm_unreachable("unknown target shuffle node");
4553   }
4554
4555   // If we have a fake unary shuffle, the shuffle mask is spread across two
4556   // inputs that are actually the same node. Re-map the mask to always point
4557   // into the first input.
4558   if (IsFakeUnary)
4559     for (int &M : Mask)
4560       if (M >= (int)Mask.size())
4561         M -= Mask.size();
4562
4563   return true;
4564 }
4565
4566 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4567 /// element of the result of the vector shuffle.
4568 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4569                                    unsigned Depth) {
4570   if (Depth == 6)
4571     return SDValue();  // Limit search depth.
4572
4573   SDValue V = SDValue(N, 0);
4574   EVT VT = V.getValueType();
4575   unsigned Opcode = V.getOpcode();
4576
4577   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4578   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4579     int Elt = SV->getMaskElt(Index);
4580
4581     if (Elt < 0)
4582       return DAG.getUNDEF(VT.getVectorElementType());
4583
4584     unsigned NumElems = VT.getVectorNumElements();
4585     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4586                                          : SV->getOperand(1);
4587     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4588   }
4589
4590   // Recurse into target specific vector shuffles to find scalars.
4591   if (isTargetShuffle(Opcode)) {
4592     MVT ShufVT = V.getSimpleValueType();
4593     unsigned NumElems = ShufVT.getVectorNumElements();
4594     SmallVector<int, 16> ShuffleMask;
4595     bool IsUnary;
4596
4597     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4598       return SDValue();
4599
4600     int Elt = ShuffleMask[Index];
4601     if (Elt < 0)
4602       return DAG.getUNDEF(ShufVT.getVectorElementType());
4603
4604     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4605                                          : N->getOperand(1);
4606     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4607                                Depth+1);
4608   }
4609
4610   // Actual nodes that may contain scalar elements
4611   if (Opcode == ISD::BITCAST) {
4612     V = V.getOperand(0);
4613     EVT SrcVT = V.getValueType();
4614     unsigned NumElems = VT.getVectorNumElements();
4615
4616     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4617       return SDValue();
4618   }
4619
4620   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4621     return (Index == 0) ? V.getOperand(0)
4622                         : DAG.getUNDEF(VT.getVectorElementType());
4623
4624   if (V.getOpcode() == ISD::BUILD_VECTOR)
4625     return V.getOperand(Index);
4626
4627   return SDValue();
4628 }
4629
4630 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4631 ///
4632 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4633                                        unsigned NumNonZero, unsigned NumZero,
4634                                        SelectionDAG &DAG,
4635                                        const X86Subtarget* Subtarget,
4636                                        const TargetLowering &TLI) {
4637   if (NumNonZero > 8)
4638     return SDValue();
4639
4640   SDLoc dl(Op);
4641   SDValue V;
4642   bool First = true;
4643
4644   // SSE4.1 - use PINSRB to insert each byte directly.
4645   if (Subtarget->hasSSE41()) {
4646     for (unsigned i = 0; i < 16; ++i) {
4647       bool isNonZero = (NonZeros & (1 << i)) != 0;
4648       if (isNonZero) {
4649         if (First) {
4650           if (NumZero)
4651             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4652           else
4653             V = DAG.getUNDEF(MVT::v16i8);
4654           First = false;
4655         }
4656         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4657                         MVT::v16i8, V, Op.getOperand(i),
4658                         DAG.getIntPtrConstant(i, dl));
4659       }
4660     }
4661
4662     return V;
4663   }
4664
4665   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4666   for (unsigned i = 0; i < 16; ++i) {
4667     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4668     if (ThisIsNonZero && First) {
4669       if (NumZero)
4670         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4671       else
4672         V = DAG.getUNDEF(MVT::v8i16);
4673       First = false;
4674     }
4675
4676     if ((i & 1) != 0) {
4677       SDValue ThisElt, LastElt;
4678       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4679       if (LastIsNonZero) {
4680         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4681                               MVT::i16, Op.getOperand(i-1));
4682       }
4683       if (ThisIsNonZero) {
4684         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4685         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4686                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4687         if (LastIsNonZero)
4688           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4689       } else
4690         ThisElt = LastElt;
4691
4692       if (ThisElt.getNode())
4693         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4694                         DAG.getIntPtrConstant(i/2, dl));
4695     }
4696   }
4697
4698   return DAG.getBitcast(MVT::v16i8, V);
4699 }
4700
4701 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4702 ///
4703 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4704                                      unsigned NumNonZero, unsigned NumZero,
4705                                      SelectionDAG &DAG,
4706                                      const X86Subtarget* Subtarget,
4707                                      const TargetLowering &TLI) {
4708   if (NumNonZero > 4)
4709     return SDValue();
4710
4711   SDLoc dl(Op);
4712   SDValue V;
4713   bool First = true;
4714   for (unsigned i = 0; i < 8; ++i) {
4715     bool isNonZero = (NonZeros & (1 << i)) != 0;
4716     if (isNonZero) {
4717       if (First) {
4718         if (NumZero)
4719           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4720         else
4721           V = DAG.getUNDEF(MVT::v8i16);
4722         First = false;
4723       }
4724       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4725                       MVT::v8i16, V, Op.getOperand(i),
4726                       DAG.getIntPtrConstant(i, dl));
4727     }
4728   }
4729
4730   return V;
4731 }
4732
4733 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4734 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4735                                      const X86Subtarget *Subtarget,
4736                                      const TargetLowering &TLI) {
4737   // Find all zeroable elements.
4738   std::bitset<4> Zeroable;
4739   for (int i=0; i < 4; ++i) {
4740     SDValue Elt = Op->getOperand(i);
4741     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4742   }
4743   assert(Zeroable.size() - Zeroable.count() > 1 &&
4744          "We expect at least two non-zero elements!");
4745
4746   // We only know how to deal with build_vector nodes where elements are either
4747   // zeroable or extract_vector_elt with constant index.
4748   SDValue FirstNonZero;
4749   unsigned FirstNonZeroIdx;
4750   for (unsigned i=0; i < 4; ++i) {
4751     if (Zeroable[i])
4752       continue;
4753     SDValue Elt = Op->getOperand(i);
4754     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4755         !isa<ConstantSDNode>(Elt.getOperand(1)))
4756       return SDValue();
4757     // Make sure that this node is extracting from a 128-bit vector.
4758     MVT VT = Elt.getOperand(0).getSimpleValueType();
4759     if (!VT.is128BitVector())
4760       return SDValue();
4761     if (!FirstNonZero.getNode()) {
4762       FirstNonZero = Elt;
4763       FirstNonZeroIdx = i;
4764     }
4765   }
4766
4767   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4768   SDValue V1 = FirstNonZero.getOperand(0);
4769   MVT VT = V1.getSimpleValueType();
4770
4771   // See if this build_vector can be lowered as a blend with zero.
4772   SDValue Elt;
4773   unsigned EltMaskIdx, EltIdx;
4774   int Mask[4];
4775   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4776     if (Zeroable[EltIdx]) {
4777       // The zero vector will be on the right hand side.
4778       Mask[EltIdx] = EltIdx+4;
4779       continue;
4780     }
4781
4782     Elt = Op->getOperand(EltIdx);
4783     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4784     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4785     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4786       break;
4787     Mask[EltIdx] = EltIdx;
4788   }
4789
4790   if (EltIdx == 4) {
4791     // Let the shuffle legalizer deal with blend operations.
4792     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4793     if (V1.getSimpleValueType() != VT)
4794       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4795     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4796   }
4797
4798   // See if we can lower this build_vector to a INSERTPS.
4799   if (!Subtarget->hasSSE41())
4800     return SDValue();
4801
4802   SDValue V2 = Elt.getOperand(0);
4803   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4804     V1 = SDValue();
4805
4806   bool CanFold = true;
4807   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4808     if (Zeroable[i])
4809       continue;
4810
4811     SDValue Current = Op->getOperand(i);
4812     SDValue SrcVector = Current->getOperand(0);
4813     if (!V1.getNode())
4814       V1 = SrcVector;
4815     CanFold = SrcVector == V1 &&
4816       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4817   }
4818
4819   if (!CanFold)
4820     return SDValue();
4821
4822   assert(V1.getNode() && "Expected at least two non-zero elements!");
4823   if (V1.getSimpleValueType() != MVT::v4f32)
4824     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4825   if (V2.getSimpleValueType() != MVT::v4f32)
4826     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4827
4828   // Ok, we can emit an INSERTPS instruction.
4829   unsigned ZMask = Zeroable.to_ulong();
4830
4831   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4832   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4833   SDLoc DL(Op);
4834   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4835                                DAG.getIntPtrConstant(InsertPSMask, DL));
4836   return DAG.getBitcast(VT, Result);
4837 }
4838
4839 /// Return a vector logical shift node.
4840 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4841                          unsigned NumBits, SelectionDAG &DAG,
4842                          const TargetLowering &TLI, SDLoc dl) {
4843   assert(VT.is128BitVector() && "Unknown type for VShift");
4844   MVT ShVT = MVT::v2i64;
4845   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4846   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4847   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4848   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4849   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4850   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4851 }
4852
4853 static SDValue
4854 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4855
4856   // Check if the scalar load can be widened into a vector load. And if
4857   // the address is "base + cst" see if the cst can be "absorbed" into
4858   // the shuffle mask.
4859   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4860     SDValue Ptr = LD->getBasePtr();
4861     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4862       return SDValue();
4863     EVT PVT = LD->getValueType(0);
4864     if (PVT != MVT::i32 && PVT != MVT::f32)
4865       return SDValue();
4866
4867     int FI = -1;
4868     int64_t Offset = 0;
4869     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4870       FI = FINode->getIndex();
4871       Offset = 0;
4872     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4873                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4874       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4875       Offset = Ptr.getConstantOperandVal(1);
4876       Ptr = Ptr.getOperand(0);
4877     } else {
4878       return SDValue();
4879     }
4880
4881     // FIXME: 256-bit vector instructions don't require a strict alignment,
4882     // improve this code to support it better.
4883     unsigned RequiredAlign = VT.getSizeInBits()/8;
4884     SDValue Chain = LD->getChain();
4885     // Make sure the stack object alignment is at least 16 or 32.
4886     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4887     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4888       if (MFI->isFixedObjectIndex(FI)) {
4889         // Can't change the alignment. FIXME: It's possible to compute
4890         // the exact stack offset and reference FI + adjust offset instead.
4891         // If someone *really* cares about this. That's the way to implement it.
4892         return SDValue();
4893       } else {
4894         MFI->setObjectAlignment(FI, RequiredAlign);
4895       }
4896     }
4897
4898     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4899     // Ptr + (Offset & ~15).
4900     if (Offset < 0)
4901       return SDValue();
4902     if ((Offset % RequiredAlign) & 3)
4903       return SDValue();
4904     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4905     if (StartOffset) {
4906       SDLoc DL(Ptr);
4907       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4908                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4909     }
4910
4911     int EltNo = (Offset - StartOffset) >> 2;
4912     unsigned NumElems = VT.getVectorNumElements();
4913
4914     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4915     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4916                              LD->getPointerInfo().getWithOffset(StartOffset),
4917                              false, false, false, 0);
4918
4919     SmallVector<int, 8> Mask(NumElems, EltNo);
4920
4921     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4922   }
4923
4924   return SDValue();
4925 }
4926
4927 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4928 /// elements can be replaced by a single large load which has the same value as
4929 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4930 ///
4931 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4932 ///
4933 /// FIXME: we'd also like to handle the case where the last elements are zero
4934 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4935 /// There's even a handy isZeroNode for that purpose.
4936 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4937                                         SDLoc &DL, SelectionDAG &DAG,
4938                                         bool isAfterLegalize) {
4939   unsigned NumElems = Elts.size();
4940
4941   LoadSDNode *LDBase = nullptr;
4942   unsigned LastLoadedElt = -1U;
4943
4944   // For each element in the initializer, see if we've found a load or an undef.
4945   // If we don't find an initial load element, or later load elements are
4946   // non-consecutive, bail out.
4947   for (unsigned i = 0; i < NumElems; ++i) {
4948     SDValue Elt = Elts[i];
4949     // Look through a bitcast.
4950     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4951       Elt = Elt.getOperand(0);
4952     if (!Elt.getNode() ||
4953         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4954       return SDValue();
4955     if (!LDBase) {
4956       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4957         return SDValue();
4958       LDBase = cast<LoadSDNode>(Elt.getNode());
4959       LastLoadedElt = i;
4960       continue;
4961     }
4962     if (Elt.getOpcode() == ISD::UNDEF)
4963       continue;
4964
4965     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4966     EVT LdVT = Elt.getValueType();
4967     // Each loaded element must be the correct fractional portion of the
4968     // requested vector load.
4969     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4970       return SDValue();
4971     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4972       return SDValue();
4973     LastLoadedElt = i;
4974   }
4975
4976   // If we have found an entire vector of loads and undefs, then return a large
4977   // load of the entire vector width starting at the base pointer.  If we found
4978   // consecutive loads for the low half, generate a vzext_load node.
4979   if (LastLoadedElt == NumElems - 1) {
4980     assert(LDBase && "Did not find base load for merging consecutive loads");
4981     EVT EltVT = LDBase->getValueType(0);
4982     // Ensure that the input vector size for the merged loads matches the
4983     // cumulative size of the input elements.
4984     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4985       return SDValue();
4986
4987     if (isAfterLegalize &&
4988         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4989       return SDValue();
4990
4991     SDValue NewLd = SDValue();
4992
4993     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4994                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4995                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4996                         LDBase->getAlignment());
4997
4998     if (LDBase->hasAnyUseOfValue(1)) {
4999       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5000                                      SDValue(LDBase, 1),
5001                                      SDValue(NewLd.getNode(), 1));
5002       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5003       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5004                              SDValue(NewLd.getNode(), 1));
5005     }
5006
5007     return NewLd;
5008   }
5009
5010   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5011   //of a v4i32 / v4f32. It's probably worth generalizing.
5012   EVT EltVT = VT.getVectorElementType();
5013   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5014       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5015     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5016     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5017     SDValue ResNode =
5018         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5019                                 LDBase->getPointerInfo(),
5020                                 LDBase->getAlignment(),
5021                                 false/*isVolatile*/, true/*ReadMem*/,
5022                                 false/*WriteMem*/);
5023
5024     // Make sure the newly-created LOAD is in the same position as LDBase in
5025     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5026     // update uses of LDBase's output chain to use the TokenFactor.
5027     if (LDBase->hasAnyUseOfValue(1)) {
5028       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5029                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5030       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5031       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5032                              SDValue(ResNode.getNode(), 1));
5033     }
5034
5035     return DAG.getBitcast(VT, ResNode);
5036   }
5037   return SDValue();
5038 }
5039
5040 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5041 /// to generate a splat value for the following cases:
5042 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5043 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5044 /// a scalar load, or a constant.
5045 /// The VBROADCAST node is returned when a pattern is found,
5046 /// or SDValue() otherwise.
5047 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5048                                     SelectionDAG &DAG) {
5049   // VBROADCAST requires AVX.
5050   // TODO: Splats could be generated for non-AVX CPUs using SSE
5051   // instructions, but there's less potential gain for only 128-bit vectors.
5052   if (!Subtarget->hasAVX())
5053     return SDValue();
5054
5055   MVT VT = Op.getSimpleValueType();
5056   SDLoc dl(Op);
5057
5058   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5059          "Unsupported vector type for broadcast.");
5060
5061   SDValue Ld;
5062   bool ConstSplatVal;
5063
5064   switch (Op.getOpcode()) {
5065     default:
5066       // Unknown pattern found.
5067       return SDValue();
5068
5069     case ISD::BUILD_VECTOR: {
5070       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5071       BitVector UndefElements;
5072       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5073
5074       // We need a splat of a single value to use broadcast, and it doesn't
5075       // make any sense if the value is only in one element of the vector.
5076       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5077         return SDValue();
5078
5079       Ld = Splat;
5080       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5081                        Ld.getOpcode() == ISD::ConstantFP);
5082
5083       // Make sure that all of the users of a non-constant load are from the
5084       // BUILD_VECTOR node.
5085       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5086         return SDValue();
5087       break;
5088     }
5089
5090     case ISD::VECTOR_SHUFFLE: {
5091       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5092
5093       // Shuffles must have a splat mask where the first element is
5094       // broadcasted.
5095       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5096         return SDValue();
5097
5098       SDValue Sc = Op.getOperand(0);
5099       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5100           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5101
5102         if (!Subtarget->hasInt256())
5103           return SDValue();
5104
5105         // Use the register form of the broadcast instruction available on AVX2.
5106         if (VT.getSizeInBits() >= 256)
5107           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5108         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5109       }
5110
5111       Ld = Sc.getOperand(0);
5112       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5113                        Ld.getOpcode() == ISD::ConstantFP);
5114
5115       // The scalar_to_vector node and the suspected
5116       // load node must have exactly one user.
5117       // Constants may have multiple users.
5118
5119       // AVX-512 has register version of the broadcast
5120       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5121         Ld.getValueType().getSizeInBits() >= 32;
5122       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5123           !hasRegVer))
5124         return SDValue();
5125       break;
5126     }
5127   }
5128
5129   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5130   bool IsGE256 = (VT.getSizeInBits() >= 256);
5131
5132   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5133   // instruction to save 8 or more bytes of constant pool data.
5134   // TODO: If multiple splats are generated to load the same constant,
5135   // it may be detrimental to overall size. There needs to be a way to detect
5136   // that condition to know if this is truly a size win.
5137   const Function *F = DAG.getMachineFunction().getFunction();
5138   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5139
5140   // Handle broadcasting a single constant scalar from the constant pool
5141   // into a vector.
5142   // On Sandybridge (no AVX2), it is still better to load a constant vector
5143   // from the constant pool and not to broadcast it from a scalar.
5144   // But override that restriction when optimizing for size.
5145   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5146   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5147     EVT CVT = Ld.getValueType();
5148     assert(!CVT.isVector() && "Must not broadcast a vector type");
5149
5150     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5151     // For size optimization, also splat v2f64 and v2i64, and for size opt
5152     // with AVX2, also splat i8 and i16.
5153     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5154     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5155         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5156       const Constant *C = nullptr;
5157       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5158         C = CI->getConstantIntValue();
5159       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5160         C = CF->getConstantFPValue();
5161
5162       assert(C && "Invalid constant type");
5163
5164       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5165       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5166       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5167       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5168                        MachinePointerInfo::getConstantPool(),
5169                        false, false, false, Alignment);
5170
5171       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5172     }
5173   }
5174
5175   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5176
5177   // Handle AVX2 in-register broadcasts.
5178   if (!IsLoad && Subtarget->hasInt256() &&
5179       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5180     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5181
5182   // The scalar source must be a normal load.
5183   if (!IsLoad)
5184     return SDValue();
5185
5186   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5187       (Subtarget->hasVLX() && ScalarSize == 64))
5188     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5189
5190   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5191   // double since there is no vbroadcastsd xmm
5192   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5193     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5194       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5195   }
5196
5197   // Unsupported broadcast.
5198   return SDValue();
5199 }
5200
5201 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5202 /// underlying vector and index.
5203 ///
5204 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5205 /// index.
5206 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5207                                          SDValue ExtIdx) {
5208   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5209   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5210     return Idx;
5211
5212   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5213   // lowered this:
5214   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5215   // to:
5216   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5217   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5218   //                           undef)
5219   //                       Constant<0>)
5220   // In this case the vector is the extract_subvector expression and the index
5221   // is 2, as specified by the shuffle.
5222   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5223   SDValue ShuffleVec = SVOp->getOperand(0);
5224   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5225   assert(ShuffleVecVT.getVectorElementType() ==
5226          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5227
5228   int ShuffleIdx = SVOp->getMaskElt(Idx);
5229   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5230     ExtractedFromVec = ShuffleVec;
5231     return ShuffleIdx;
5232   }
5233   return Idx;
5234 }
5235
5236 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5237   MVT VT = Op.getSimpleValueType();
5238
5239   // Skip if insert_vec_elt is not supported.
5240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5241   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5242     return SDValue();
5243
5244   SDLoc DL(Op);
5245   unsigned NumElems = Op.getNumOperands();
5246
5247   SDValue VecIn1;
5248   SDValue VecIn2;
5249   SmallVector<unsigned, 4> InsertIndices;
5250   SmallVector<int, 8> Mask(NumElems, -1);
5251
5252   for (unsigned i = 0; i != NumElems; ++i) {
5253     unsigned Opc = Op.getOperand(i).getOpcode();
5254
5255     if (Opc == ISD::UNDEF)
5256       continue;
5257
5258     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5259       // Quit if more than 1 elements need inserting.
5260       if (InsertIndices.size() > 1)
5261         return SDValue();
5262
5263       InsertIndices.push_back(i);
5264       continue;
5265     }
5266
5267     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5268     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5269     // Quit if non-constant index.
5270     if (!isa<ConstantSDNode>(ExtIdx))
5271       return SDValue();
5272     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5273
5274     // Quit if extracted from vector of different type.
5275     if (ExtractedFromVec.getValueType() != VT)
5276       return SDValue();
5277
5278     if (!VecIn1.getNode())
5279       VecIn1 = ExtractedFromVec;
5280     else if (VecIn1 != ExtractedFromVec) {
5281       if (!VecIn2.getNode())
5282         VecIn2 = ExtractedFromVec;
5283       else if (VecIn2 != ExtractedFromVec)
5284         // Quit if more than 2 vectors to shuffle
5285         return SDValue();
5286     }
5287
5288     if (ExtractedFromVec == VecIn1)
5289       Mask[i] = Idx;
5290     else if (ExtractedFromVec == VecIn2)
5291       Mask[i] = Idx + NumElems;
5292   }
5293
5294   if (!VecIn1.getNode())
5295     return SDValue();
5296
5297   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5298   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5299   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5300     unsigned Idx = InsertIndices[i];
5301     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5302                      DAG.getIntPtrConstant(Idx, DL));
5303   }
5304
5305   return NV;
5306 }
5307
5308 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5309   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5310          Op.getScalarValueSizeInBits() == 1 &&
5311          "Can not convert non-constant vector");
5312   uint64_t Immediate = 0;
5313   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5314     SDValue In = Op.getOperand(idx);
5315     if (In.getOpcode() != ISD::UNDEF)
5316       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5317   }
5318   SDLoc dl(Op);
5319   MVT VT =
5320    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5321   return DAG.getConstant(Immediate, dl, VT);
5322 }
5323 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5324 SDValue
5325 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5326
5327   MVT VT = Op.getSimpleValueType();
5328   assert((VT.getVectorElementType() == MVT::i1) &&
5329          "Unexpected type in LowerBUILD_VECTORvXi1!");
5330
5331   SDLoc dl(Op);
5332   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5333     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5334     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5335     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5336   }
5337
5338   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5339     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5340     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5341     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5342   }
5343
5344   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5345     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5346     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5347       return DAG.getBitcast(VT, Imm);
5348     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5349     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5350                         DAG.getIntPtrConstant(0, dl));
5351   }
5352
5353   // Vector has one or more non-const elements
5354   uint64_t Immediate = 0;
5355   SmallVector<unsigned, 16> NonConstIdx;
5356   bool IsSplat = true;
5357   bool HasConstElts = false;
5358   int SplatIdx = -1;
5359   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5360     SDValue In = Op.getOperand(idx);
5361     if (In.getOpcode() == ISD::UNDEF)
5362       continue;
5363     if (!isa<ConstantSDNode>(In))
5364       NonConstIdx.push_back(idx);
5365     else {
5366       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5367       HasConstElts = true;
5368     }
5369     if (SplatIdx == -1)
5370       SplatIdx = idx;
5371     else if (In != Op.getOperand(SplatIdx))
5372       IsSplat = false;
5373   }
5374
5375   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5376   if (IsSplat)
5377     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5378                        DAG.getConstant(1, dl, VT),
5379                        DAG.getConstant(0, dl, VT));
5380
5381   // insert elements one by one
5382   SDValue DstVec;
5383   SDValue Imm;
5384   if (Immediate) {
5385     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5386     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5387   }
5388   else if (HasConstElts)
5389     Imm = DAG.getConstant(0, dl, VT);
5390   else
5391     Imm = DAG.getUNDEF(VT);
5392   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5393     DstVec = DAG.getBitcast(VT, Imm);
5394   else {
5395     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5396     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5397                          DAG.getIntPtrConstant(0, dl));
5398   }
5399
5400   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5401     unsigned InsertIdx = NonConstIdx[i];
5402     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5403                          Op.getOperand(InsertIdx),
5404                          DAG.getIntPtrConstant(InsertIdx, dl));
5405   }
5406   return DstVec;
5407 }
5408
5409 /// \brief Return true if \p N implements a horizontal binop and return the
5410 /// operands for the horizontal binop into V0 and V1.
5411 ///
5412 /// This is a helper function of LowerToHorizontalOp().
5413 /// This function checks that the build_vector \p N in input implements a
5414 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5415 /// operation to match.
5416 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5417 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5418 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5419 /// arithmetic sub.
5420 ///
5421 /// This function only analyzes elements of \p N whose indices are
5422 /// in range [BaseIdx, LastIdx).
5423 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5424                               SelectionDAG &DAG,
5425                               unsigned BaseIdx, unsigned LastIdx,
5426                               SDValue &V0, SDValue &V1) {
5427   EVT VT = N->getValueType(0);
5428
5429   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5430   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5431          "Invalid Vector in input!");
5432
5433   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5434   bool CanFold = true;
5435   unsigned ExpectedVExtractIdx = BaseIdx;
5436   unsigned NumElts = LastIdx - BaseIdx;
5437   V0 = DAG.getUNDEF(VT);
5438   V1 = DAG.getUNDEF(VT);
5439
5440   // Check if N implements a horizontal binop.
5441   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5442     SDValue Op = N->getOperand(i + BaseIdx);
5443
5444     // Skip UNDEFs.
5445     if (Op->getOpcode() == ISD::UNDEF) {
5446       // Update the expected vector extract index.
5447       if (i * 2 == NumElts)
5448         ExpectedVExtractIdx = BaseIdx;
5449       ExpectedVExtractIdx += 2;
5450       continue;
5451     }
5452
5453     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5454
5455     if (!CanFold)
5456       break;
5457
5458     SDValue Op0 = Op.getOperand(0);
5459     SDValue Op1 = Op.getOperand(1);
5460
5461     // Try to match the following pattern:
5462     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5463     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5464         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5465         Op0.getOperand(0) == Op1.getOperand(0) &&
5466         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5467         isa<ConstantSDNode>(Op1.getOperand(1)));
5468     if (!CanFold)
5469       break;
5470
5471     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5472     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5473
5474     if (i * 2 < NumElts) {
5475       if (V0.getOpcode() == ISD::UNDEF) {
5476         V0 = Op0.getOperand(0);
5477         if (V0.getValueType() != VT)
5478           return false;
5479       }
5480     } else {
5481       if (V1.getOpcode() == ISD::UNDEF) {
5482         V1 = Op0.getOperand(0);
5483         if (V1.getValueType() != VT)
5484           return false;
5485       }
5486       if (i * 2 == NumElts)
5487         ExpectedVExtractIdx = BaseIdx;
5488     }
5489
5490     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5491     if (I0 == ExpectedVExtractIdx)
5492       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5493     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5494       // Try to match the following dag sequence:
5495       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5496       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5497     } else
5498       CanFold = false;
5499
5500     ExpectedVExtractIdx += 2;
5501   }
5502
5503   return CanFold;
5504 }
5505
5506 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5507 /// a concat_vector.
5508 ///
5509 /// This is a helper function of LowerToHorizontalOp().
5510 /// This function expects two 256-bit vectors called V0 and V1.
5511 /// At first, each vector is split into two separate 128-bit vectors.
5512 /// Then, the resulting 128-bit vectors are used to implement two
5513 /// horizontal binary operations.
5514 ///
5515 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5516 ///
5517 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5518 /// the two new horizontal binop.
5519 /// When Mode is set, the first horizontal binop dag node would take as input
5520 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5521 /// horizontal binop dag node would take as input the lower 128-bit of V1
5522 /// and the upper 128-bit of V1.
5523 ///   Example:
5524 ///     HADD V0_LO, V0_HI
5525 ///     HADD V1_LO, V1_HI
5526 ///
5527 /// Otherwise, the first horizontal binop dag node takes as input the lower
5528 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5529 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5530 ///   Example:
5531 ///     HADD V0_LO, V1_LO
5532 ///     HADD V0_HI, V1_HI
5533 ///
5534 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5535 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5536 /// the upper 128-bits of the result.
5537 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5538                                      SDLoc DL, SelectionDAG &DAG,
5539                                      unsigned X86Opcode, bool Mode,
5540                                      bool isUndefLO, bool isUndefHI) {
5541   EVT VT = V0.getValueType();
5542   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5543          "Invalid nodes in input!");
5544
5545   unsigned NumElts = VT.getVectorNumElements();
5546   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5547   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5548   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5549   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5550   EVT NewVT = V0_LO.getValueType();
5551
5552   SDValue LO = DAG.getUNDEF(NewVT);
5553   SDValue HI = DAG.getUNDEF(NewVT);
5554
5555   if (Mode) {
5556     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5557     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5558       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5559     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5560       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5561   } else {
5562     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5563     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5564                        V1_LO->getOpcode() != ISD::UNDEF))
5565       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5566
5567     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5568                        V1_HI->getOpcode() != ISD::UNDEF))
5569       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5570   }
5571
5572   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5573 }
5574
5575 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5576 /// node.
5577 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5578                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5579   EVT VT = BV->getValueType(0);
5580   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5581       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5582     return SDValue();
5583
5584   SDLoc DL(BV);
5585   unsigned NumElts = VT.getVectorNumElements();
5586   SDValue InVec0 = DAG.getUNDEF(VT);
5587   SDValue InVec1 = DAG.getUNDEF(VT);
5588
5589   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5590           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5591
5592   // Odd-numbered elements in the input build vector are obtained from
5593   // adding two integer/float elements.
5594   // Even-numbered elements in the input build vector are obtained from
5595   // subtracting two integer/float elements.
5596   unsigned ExpectedOpcode = ISD::FSUB;
5597   unsigned NextExpectedOpcode = ISD::FADD;
5598   bool AddFound = false;
5599   bool SubFound = false;
5600
5601   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5602     SDValue Op = BV->getOperand(i);
5603
5604     // Skip 'undef' values.
5605     unsigned Opcode = Op.getOpcode();
5606     if (Opcode == ISD::UNDEF) {
5607       std::swap(ExpectedOpcode, NextExpectedOpcode);
5608       continue;
5609     }
5610
5611     // Early exit if we found an unexpected opcode.
5612     if (Opcode != ExpectedOpcode)
5613       return SDValue();
5614
5615     SDValue Op0 = Op.getOperand(0);
5616     SDValue Op1 = Op.getOperand(1);
5617
5618     // Try to match the following pattern:
5619     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5620     // Early exit if we cannot match that sequence.
5621     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5622         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5623         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5624         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5625         Op0.getOperand(1) != Op1.getOperand(1))
5626       return SDValue();
5627
5628     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5629     if (I0 != i)
5630       return SDValue();
5631
5632     // We found a valid add/sub node. Update the information accordingly.
5633     if (i & 1)
5634       AddFound = true;
5635     else
5636       SubFound = true;
5637
5638     // Update InVec0 and InVec1.
5639     if (InVec0.getOpcode() == ISD::UNDEF) {
5640       InVec0 = Op0.getOperand(0);
5641       if (InVec0.getValueType() != VT)
5642         return SDValue();
5643     }
5644     if (InVec1.getOpcode() == ISD::UNDEF) {
5645       InVec1 = Op1.getOperand(0);
5646       if (InVec1.getValueType() != VT)
5647         return SDValue();
5648     }
5649
5650     // Make sure that operands in input to each add/sub node always
5651     // come from a same pair of vectors.
5652     if (InVec0 != Op0.getOperand(0)) {
5653       if (ExpectedOpcode == ISD::FSUB)
5654         return SDValue();
5655
5656       // FADD is commutable. Try to commute the operands
5657       // and then test again.
5658       std::swap(Op0, Op1);
5659       if (InVec0 != Op0.getOperand(0))
5660         return SDValue();
5661     }
5662
5663     if (InVec1 != Op1.getOperand(0))
5664       return SDValue();
5665
5666     // Update the pair of expected opcodes.
5667     std::swap(ExpectedOpcode, NextExpectedOpcode);
5668   }
5669
5670   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5671   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5672       InVec1.getOpcode() != ISD::UNDEF)
5673     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5674
5675   return SDValue();
5676 }
5677
5678 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5679 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5680                                    const X86Subtarget *Subtarget,
5681                                    SelectionDAG &DAG) {
5682   EVT VT = BV->getValueType(0);
5683   unsigned NumElts = VT.getVectorNumElements();
5684   unsigned NumUndefsLO = 0;
5685   unsigned NumUndefsHI = 0;
5686   unsigned Half = NumElts/2;
5687
5688   // Count the number of UNDEF operands in the build_vector in input.
5689   for (unsigned i = 0, e = Half; i != e; ++i)
5690     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5691       NumUndefsLO++;
5692
5693   for (unsigned i = Half, e = NumElts; i != e; ++i)
5694     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5695       NumUndefsHI++;
5696
5697   // Early exit if this is either a build_vector of all UNDEFs or all the
5698   // operands but one are UNDEF.
5699   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5700     return SDValue();
5701
5702   SDLoc DL(BV);
5703   SDValue InVec0, InVec1;
5704   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5705     // Try to match an SSE3 float HADD/HSUB.
5706     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5707       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5708
5709     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5710       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5711   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5712     // Try to match an SSSE3 integer HADD/HSUB.
5713     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5714       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5715
5716     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5717       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5718   }
5719
5720   if (!Subtarget->hasAVX())
5721     return SDValue();
5722
5723   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5724     // Try to match an AVX horizontal add/sub of packed single/double
5725     // precision floating point values from 256-bit vectors.
5726     SDValue InVec2, InVec3;
5727     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5728         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5729         ((InVec0.getOpcode() == ISD::UNDEF ||
5730           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5731         ((InVec1.getOpcode() == ISD::UNDEF ||
5732           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5733       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5734
5735     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5736         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5737         ((InVec0.getOpcode() == ISD::UNDEF ||
5738           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5739         ((InVec1.getOpcode() == ISD::UNDEF ||
5740           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5741       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5742   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5743     // Try to match an AVX2 horizontal add/sub of signed integers.
5744     SDValue InVec2, InVec3;
5745     unsigned X86Opcode;
5746     bool CanFold = true;
5747
5748     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5749         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5750         ((InVec0.getOpcode() == ISD::UNDEF ||
5751           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5752         ((InVec1.getOpcode() == ISD::UNDEF ||
5753           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5754       X86Opcode = X86ISD::HADD;
5755     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5756         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5757         ((InVec0.getOpcode() == ISD::UNDEF ||
5758           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5759         ((InVec1.getOpcode() == ISD::UNDEF ||
5760           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5761       X86Opcode = X86ISD::HSUB;
5762     else
5763       CanFold = false;
5764
5765     if (CanFold) {
5766       // Fold this build_vector into a single horizontal add/sub.
5767       // Do this only if the target has AVX2.
5768       if (Subtarget->hasAVX2())
5769         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5770
5771       // Do not try to expand this build_vector into a pair of horizontal
5772       // add/sub if we can emit a pair of scalar add/sub.
5773       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5774         return SDValue();
5775
5776       // Convert this build_vector into a pair of horizontal binop followed by
5777       // a concat vector.
5778       bool isUndefLO = NumUndefsLO == Half;
5779       bool isUndefHI = NumUndefsHI == Half;
5780       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5781                                    isUndefLO, isUndefHI);
5782     }
5783   }
5784
5785   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5786        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5787     unsigned X86Opcode;
5788     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5789       X86Opcode = X86ISD::HADD;
5790     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5791       X86Opcode = X86ISD::HSUB;
5792     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5793       X86Opcode = X86ISD::FHADD;
5794     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5795       X86Opcode = X86ISD::FHSUB;
5796     else
5797       return SDValue();
5798
5799     // Don't try to expand this build_vector into a pair of horizontal add/sub
5800     // if we can simply emit a pair of scalar add/sub.
5801     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5802       return SDValue();
5803
5804     // Convert this build_vector into two horizontal add/sub followed by
5805     // a concat vector.
5806     bool isUndefLO = NumUndefsLO == Half;
5807     bool isUndefHI = NumUndefsHI == Half;
5808     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5809                                  isUndefLO, isUndefHI);
5810   }
5811
5812   return SDValue();
5813 }
5814
5815 SDValue
5816 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5817   SDLoc dl(Op);
5818
5819   MVT VT = Op.getSimpleValueType();
5820   MVT ExtVT = VT.getVectorElementType();
5821   unsigned NumElems = Op.getNumOperands();
5822
5823   // Generate vectors for predicate vectors.
5824   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5825     return LowerBUILD_VECTORvXi1(Op, DAG);
5826
5827   // Vectors containing all zeros can be matched by pxor and xorps later
5828   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5829     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5830     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5831     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5832       return Op;
5833
5834     return getZeroVector(VT, Subtarget, DAG, dl);
5835   }
5836
5837   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5838   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5839   // vpcmpeqd on 256-bit vectors.
5840   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5841     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5842       return Op;
5843
5844     if (!VT.is512BitVector())
5845       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5846   }
5847
5848   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5849   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5850     return AddSub;
5851   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5852     return HorizontalOp;
5853   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5854     return Broadcast;
5855
5856   unsigned EVTBits = ExtVT.getSizeInBits();
5857
5858   unsigned NumZero  = 0;
5859   unsigned NumNonZero = 0;
5860   unsigned NonZeros = 0;
5861   bool IsAllConstants = true;
5862   SmallSet<SDValue, 8> Values;
5863   for (unsigned i = 0; i < NumElems; ++i) {
5864     SDValue Elt = Op.getOperand(i);
5865     if (Elt.getOpcode() == ISD::UNDEF)
5866       continue;
5867     Values.insert(Elt);
5868     if (Elt.getOpcode() != ISD::Constant &&
5869         Elt.getOpcode() != ISD::ConstantFP)
5870       IsAllConstants = false;
5871     if (X86::isZeroNode(Elt))
5872       NumZero++;
5873     else {
5874       NonZeros |= (1 << i);
5875       NumNonZero++;
5876     }
5877   }
5878
5879   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5880   if (NumNonZero == 0)
5881     return DAG.getUNDEF(VT);
5882
5883   // Special case for single non-zero, non-undef, element.
5884   if (NumNonZero == 1) {
5885     unsigned Idx = countTrailingZeros(NonZeros);
5886     SDValue Item = Op.getOperand(Idx);
5887
5888     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5889     // the value are obviously zero, truncate the value to i32 and do the
5890     // insertion that way.  Only do this if the value is non-constant or if the
5891     // value is a constant being inserted into element 0.  It is cheaper to do
5892     // a constant pool load than it is to do a movd + shuffle.
5893     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5894         (!IsAllConstants || Idx == 0)) {
5895       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5896         // Handle SSE only.
5897         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5898         EVT VecVT = MVT::v4i32;
5899
5900         // Truncate the value (which may itself be a constant) to i32, and
5901         // convert it to a vector with movd (S2V+shuffle to zero extend).
5902         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5903         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5904         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5905                                       Item, Idx * 2, true, Subtarget, DAG));
5906       }
5907     }
5908
5909     // If we have a constant or non-constant insertion into the low element of
5910     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5911     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5912     // depending on what the source datatype is.
5913     if (Idx == 0) {
5914       if (NumZero == 0)
5915         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5916
5917       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5918           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5919         if (VT.is512BitVector()) {
5920           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5921           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5922                              Item, DAG.getIntPtrConstant(0, dl));
5923         }
5924         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5925                "Expected an SSE value type!");
5926         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5927         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5928         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5929       }
5930
5931       // We can't directly insert an i8 or i16 into a vector, so zero extend
5932       // it to i32 first.
5933       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5934         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5935         if (VT.is256BitVector()) {
5936           if (Subtarget->hasAVX()) {
5937             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5938             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5939           } else {
5940             // Without AVX, we need to extend to a 128-bit vector and then
5941             // insert into the 256-bit vector.
5942             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5943             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5944             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5945           }
5946         } else {
5947           assert(VT.is128BitVector() && "Expected an SSE value type!");
5948           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5949           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5950         }
5951         return DAG.getBitcast(VT, Item);
5952       }
5953     }
5954
5955     // Is it a vector logical left shift?
5956     if (NumElems == 2 && Idx == 1 &&
5957         X86::isZeroNode(Op.getOperand(0)) &&
5958         !X86::isZeroNode(Op.getOperand(1))) {
5959       unsigned NumBits = VT.getSizeInBits();
5960       return getVShift(true, VT,
5961                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5962                                    VT, Op.getOperand(1)),
5963                        NumBits/2, DAG, *this, dl);
5964     }
5965
5966     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5967       return SDValue();
5968
5969     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5970     // is a non-constant being inserted into an element other than the low one,
5971     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5972     // movd/movss) to move this into the low element, then shuffle it into
5973     // place.
5974     if (EVTBits == 32) {
5975       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5976       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5977     }
5978   }
5979
5980   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5981   if (Values.size() == 1) {
5982     if (EVTBits == 32) {
5983       // Instead of a shuffle like this:
5984       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5985       // Check if it's possible to issue this instead.
5986       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5987       unsigned Idx = countTrailingZeros(NonZeros);
5988       SDValue Item = Op.getOperand(Idx);
5989       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5990         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5991     }
5992     return SDValue();
5993   }
5994
5995   // A vector full of immediates; various special cases are already
5996   // handled, so this is best done with a single constant-pool load.
5997   if (IsAllConstants)
5998     return SDValue();
5999
6000   // For AVX-length vectors, see if we can use a vector load to get all of the
6001   // elements, otherwise build the individual 128-bit pieces and use
6002   // shuffles to put them in place.
6003   if (VT.is256BitVector() || VT.is512BitVector()) {
6004     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6005
6006     // Check for a build vector of consecutive loads.
6007     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6008       return LD;
6009
6010     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6011
6012     // Build both the lower and upper subvector.
6013     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6014                                 makeArrayRef(&V[0], NumElems/2));
6015     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6016                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6017
6018     // Recreate the wider vector with the lower and upper part.
6019     if (VT.is256BitVector())
6020       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6021     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6022   }
6023
6024   // Let legalizer expand 2-wide build_vectors.
6025   if (EVTBits == 64) {
6026     if (NumNonZero == 1) {
6027       // One half is zero or undef.
6028       unsigned Idx = countTrailingZeros(NonZeros);
6029       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6030                                  Op.getOperand(Idx));
6031       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6032     }
6033     return SDValue();
6034   }
6035
6036   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6037   if (EVTBits == 8 && NumElems == 16)
6038     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6039                                         Subtarget, *this))
6040       return V;
6041
6042   if (EVTBits == 16 && NumElems == 8)
6043     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6044                                       Subtarget, *this))
6045       return V;
6046
6047   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6048   if (EVTBits == 32 && NumElems == 4)
6049     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6050       return V;
6051
6052   // If element VT is == 32 bits, turn it into a number of shuffles.
6053   SmallVector<SDValue, 8> V(NumElems);
6054   if (NumElems == 4 && NumZero > 0) {
6055     for (unsigned i = 0; i < 4; ++i) {
6056       bool isZero = !(NonZeros & (1 << i));
6057       if (isZero)
6058         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6059       else
6060         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6061     }
6062
6063     for (unsigned i = 0; i < 2; ++i) {
6064       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6065         default: break;
6066         case 0:
6067           V[i] = V[i*2];  // Must be a zero vector.
6068           break;
6069         case 1:
6070           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6071           break;
6072         case 2:
6073           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6074           break;
6075         case 3:
6076           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6077           break;
6078       }
6079     }
6080
6081     bool Reverse1 = (NonZeros & 0x3) == 2;
6082     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6083     int MaskVec[] = {
6084       Reverse1 ? 1 : 0,
6085       Reverse1 ? 0 : 1,
6086       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6087       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6088     };
6089     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6090   }
6091
6092   if (Values.size() > 1 && VT.is128BitVector()) {
6093     // Check for a build vector of consecutive loads.
6094     for (unsigned i = 0; i < NumElems; ++i)
6095       V[i] = Op.getOperand(i);
6096
6097     // Check for elements which are consecutive loads.
6098     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6099       return LD;
6100
6101     // Check for a build vector from mostly shuffle plus few inserting.
6102     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6103       return Sh;
6104
6105     // For SSE 4.1, use insertps to put the high elements into the low element.
6106     if (Subtarget->hasSSE41()) {
6107       SDValue Result;
6108       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6109         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6110       else
6111         Result = DAG.getUNDEF(VT);
6112
6113       for (unsigned i = 1; i < NumElems; ++i) {
6114         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6115         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6116                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6117       }
6118       return Result;
6119     }
6120
6121     // Otherwise, expand into a number of unpckl*, start by extending each of
6122     // our (non-undef) elements to the full vector width with the element in the
6123     // bottom slot of the vector (which generates no code for SSE).
6124     for (unsigned i = 0; i < NumElems; ++i) {
6125       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6126         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6127       else
6128         V[i] = DAG.getUNDEF(VT);
6129     }
6130
6131     // Next, we iteratively mix elements, e.g. for v4f32:
6132     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6133     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6134     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6135     unsigned EltStride = NumElems >> 1;
6136     while (EltStride != 0) {
6137       for (unsigned i = 0; i < EltStride; ++i) {
6138         // If V[i+EltStride] is undef and this is the first round of mixing,
6139         // then it is safe to just drop this shuffle: V[i] is already in the
6140         // right place, the one element (since it's the first round) being
6141         // inserted as undef can be dropped.  This isn't safe for successive
6142         // rounds because they will permute elements within both vectors.
6143         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6144             EltStride == NumElems/2)
6145           continue;
6146
6147         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6148       }
6149       EltStride >>= 1;
6150     }
6151     return V[0];
6152   }
6153   return SDValue();
6154 }
6155
6156 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6157 // to create 256-bit vectors from two other 128-bit ones.
6158 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6159   SDLoc dl(Op);
6160   MVT ResVT = Op.getSimpleValueType();
6161
6162   assert((ResVT.is256BitVector() ||
6163           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6164
6165   SDValue V1 = Op.getOperand(0);
6166   SDValue V2 = Op.getOperand(1);
6167   unsigned NumElems = ResVT.getVectorNumElements();
6168   if (ResVT.is256BitVector())
6169     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6170
6171   if (Op.getNumOperands() == 4) {
6172     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6173                                 ResVT.getVectorNumElements()/2);
6174     SDValue V3 = Op.getOperand(2);
6175     SDValue V4 = Op.getOperand(3);
6176     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6177       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6178   }
6179   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6180 }
6181
6182 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6183                                        const X86Subtarget *Subtarget,
6184                                        SelectionDAG & DAG) {
6185   SDLoc dl(Op);
6186   MVT ResVT = Op.getSimpleValueType();
6187   unsigned NumOfOperands = Op.getNumOperands();
6188
6189   assert(isPowerOf2_32(NumOfOperands) &&
6190          "Unexpected number of operands in CONCAT_VECTORS");
6191
6192   if (NumOfOperands > 2) {
6193     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6194                                   ResVT.getVectorNumElements()/2);
6195     SmallVector<SDValue, 2> Ops;
6196     for (unsigned i = 0; i < NumOfOperands/2; i++)
6197       Ops.push_back(Op.getOperand(i));
6198     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6199     Ops.clear();
6200     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6201       Ops.push_back(Op.getOperand(i));
6202     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6203     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6204   }
6205
6206   SDValue V1 = Op.getOperand(0);
6207   SDValue V2 = Op.getOperand(1);
6208   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6209   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6210
6211   if (IsZeroV1 && IsZeroV2)
6212     return getZeroVector(ResVT, Subtarget, DAG, dl);
6213
6214   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6215   SDValue Undef = DAG.getUNDEF(ResVT);
6216   unsigned NumElems = ResVT.getVectorNumElements();
6217   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6218
6219   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6220   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6221   if (IsZeroV1)
6222     return V2;
6223
6224   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6225   // Zero the upper bits of V1
6226   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6227   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6228   if (IsZeroV2)
6229     return V1;
6230   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6231 }
6232
6233 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6234                                    const X86Subtarget *Subtarget,
6235                                    SelectionDAG &DAG) {
6236   MVT VT = Op.getSimpleValueType();
6237   if (VT.getVectorElementType() == MVT::i1)
6238     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6239
6240   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6241          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6242           Op.getNumOperands() == 4)));
6243
6244   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6245   // from two other 128-bit ones.
6246
6247   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6248   return LowerAVXCONCAT_VECTORS(Op, DAG);
6249 }
6250
6251
6252 //===----------------------------------------------------------------------===//
6253 // Vector shuffle lowering
6254 //
6255 // This is an experimental code path for lowering vector shuffles on x86. It is
6256 // designed to handle arbitrary vector shuffles and blends, gracefully
6257 // degrading performance as necessary. It works hard to recognize idiomatic
6258 // shuffles and lower them to optimal instruction patterns without leaving
6259 // a framework that allows reasonably efficient handling of all vector shuffle
6260 // patterns.
6261 //===----------------------------------------------------------------------===//
6262
6263 /// \brief Tiny helper function to identify a no-op mask.
6264 ///
6265 /// This is a somewhat boring predicate function. It checks whether the mask
6266 /// array input, which is assumed to be a single-input shuffle mask of the kind
6267 /// used by the X86 shuffle instructions (not a fully general
6268 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6269 /// in-place shuffle are 'no-op's.
6270 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6271   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6272     if (Mask[i] != -1 && Mask[i] != i)
6273       return false;
6274   return true;
6275 }
6276
6277 /// \brief Helper function to classify a mask as a single-input mask.
6278 ///
6279 /// This isn't a generic single-input test because in the vector shuffle
6280 /// lowering we canonicalize single inputs to be the first input operand. This
6281 /// means we can more quickly test for a single input by only checking whether
6282 /// an input from the second operand exists. We also assume that the size of
6283 /// mask corresponds to the size of the input vectors which isn't true in the
6284 /// fully general case.
6285 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6286   for (int M : Mask)
6287     if (M >= (int)Mask.size())
6288       return false;
6289   return true;
6290 }
6291
6292 /// \brief Test whether there are elements crossing 128-bit lanes in this
6293 /// shuffle mask.
6294 ///
6295 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6296 /// and we routinely test for these.
6297 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6298   int LaneSize = 128 / VT.getScalarSizeInBits();
6299   int Size = Mask.size();
6300   for (int i = 0; i < Size; ++i)
6301     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6302       return true;
6303   return false;
6304 }
6305
6306 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6307 ///
6308 /// This checks a shuffle mask to see if it is performing the same
6309 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6310 /// that it is also not lane-crossing. It may however involve a blend from the
6311 /// same lane of a second vector.
6312 ///
6313 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6314 /// non-trivial to compute in the face of undef lanes. The representation is
6315 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6316 /// entries from both V1 and V2 inputs to the wider mask.
6317 static bool
6318 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6319                                 SmallVectorImpl<int> &RepeatedMask) {
6320   int LaneSize = 128 / VT.getScalarSizeInBits();
6321   RepeatedMask.resize(LaneSize, -1);
6322   int Size = Mask.size();
6323   for (int i = 0; i < Size; ++i) {
6324     if (Mask[i] < 0)
6325       continue;
6326     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6327       // This entry crosses lanes, so there is no way to model this shuffle.
6328       return false;
6329
6330     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6331     if (RepeatedMask[i % LaneSize] == -1)
6332       // This is the first non-undef entry in this slot of a 128-bit lane.
6333       RepeatedMask[i % LaneSize] =
6334           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6335     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6336       // Found a mismatch with the repeated mask.
6337       return false;
6338   }
6339   return true;
6340 }
6341
6342 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6343 /// arguments.
6344 ///
6345 /// This is a fast way to test a shuffle mask against a fixed pattern:
6346 ///
6347 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6348 ///
6349 /// It returns true if the mask is exactly as wide as the argument list, and
6350 /// each element of the mask is either -1 (signifying undef) or the value given
6351 /// in the argument.
6352 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6353                                 ArrayRef<int> ExpectedMask) {
6354   if (Mask.size() != ExpectedMask.size())
6355     return false;
6356
6357   int Size = Mask.size();
6358
6359   // If the values are build vectors, we can look through them to find
6360   // equivalent inputs that make the shuffles equivalent.
6361   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6362   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6363
6364   for (int i = 0; i < Size; ++i)
6365     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6366       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6367       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6368       if (!MaskBV || !ExpectedBV ||
6369           MaskBV->getOperand(Mask[i] % Size) !=
6370               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6371         return false;
6372     }
6373
6374   return true;
6375 }
6376
6377 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6378 ///
6379 /// This helper function produces an 8-bit shuffle immediate corresponding to
6380 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6381 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6382 /// example.
6383 ///
6384 /// NB: We rely heavily on "undef" masks preserving the input lane.
6385 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6386                                           SelectionDAG &DAG) {
6387   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6388   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6389   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6390   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6391   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6392
6393   unsigned Imm = 0;
6394   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6395   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6396   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6397   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6398   return DAG.getConstant(Imm, DL, MVT::i8);
6399 }
6400
6401 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6402 ///
6403 /// This is used as a fallback approach when first class blend instructions are
6404 /// unavailable. Currently it is only suitable for integer vectors, but could
6405 /// be generalized for floating point vectors if desirable.
6406 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6407                                             SDValue V2, ArrayRef<int> Mask,
6408                                             SelectionDAG &DAG) {
6409   assert(VT.isInteger() && "Only supports integer vector types!");
6410   MVT EltVT = VT.getScalarType();
6411   int NumEltBits = EltVT.getSizeInBits();
6412   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6413   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6414                                     EltVT);
6415   SmallVector<SDValue, 16> MaskOps;
6416   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6417     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6418       return SDValue(); // Shuffled input!
6419     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6420   }
6421
6422   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6423   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6424   // We have to cast V2 around.
6425   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6426   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6427                                       DAG.getBitcast(MaskVT, V1Mask),
6428                                       DAG.getBitcast(MaskVT, V2)));
6429   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6430 }
6431
6432 /// \brief Try to emit a blend instruction for a shuffle.
6433 ///
6434 /// This doesn't do any checks for the availability of instructions for blending
6435 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6436 /// be matched in the backend with the type given. What it does check for is
6437 /// that the shuffle mask is in fact a blend.
6438 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6439                                          SDValue V2, ArrayRef<int> Mask,
6440                                          const X86Subtarget *Subtarget,
6441                                          SelectionDAG &DAG) {
6442   unsigned BlendMask = 0;
6443   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6444     if (Mask[i] >= Size) {
6445       if (Mask[i] != i + Size)
6446         return SDValue(); // Shuffled V2 input!
6447       BlendMask |= 1u << i;
6448       continue;
6449     }
6450     if (Mask[i] >= 0 && Mask[i] != i)
6451       return SDValue(); // Shuffled V1 input!
6452   }
6453   switch (VT.SimpleTy) {
6454   case MVT::v2f64:
6455   case MVT::v4f32:
6456   case MVT::v4f64:
6457   case MVT::v8f32:
6458     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6459                        DAG.getConstant(BlendMask, DL, MVT::i8));
6460
6461   case MVT::v4i64:
6462   case MVT::v8i32:
6463     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6464     // FALLTHROUGH
6465   case MVT::v2i64:
6466   case MVT::v4i32:
6467     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6468     // that instruction.
6469     if (Subtarget->hasAVX2()) {
6470       // Scale the blend by the number of 32-bit dwords per element.
6471       int Scale =  VT.getScalarSizeInBits() / 32;
6472       BlendMask = 0;
6473       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6474         if (Mask[i] >= Size)
6475           for (int j = 0; j < Scale; ++j)
6476             BlendMask |= 1u << (i * Scale + j);
6477
6478       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6479       V1 = DAG.getBitcast(BlendVT, V1);
6480       V2 = DAG.getBitcast(BlendVT, V2);
6481       return DAG.getBitcast(
6482           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6483                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6484     }
6485     // FALLTHROUGH
6486   case MVT::v8i16: {
6487     // For integer shuffles we need to expand the mask and cast the inputs to
6488     // v8i16s prior to blending.
6489     int Scale = 8 / VT.getVectorNumElements();
6490     BlendMask = 0;
6491     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6492       if (Mask[i] >= Size)
6493         for (int j = 0; j < Scale; ++j)
6494           BlendMask |= 1u << (i * Scale + j);
6495
6496     V1 = DAG.getBitcast(MVT::v8i16, V1);
6497     V2 = DAG.getBitcast(MVT::v8i16, V2);
6498     return DAG.getBitcast(VT,
6499                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6500                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6501   }
6502
6503   case MVT::v16i16: {
6504     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6505     SmallVector<int, 8> RepeatedMask;
6506     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6507       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6508       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6509       BlendMask = 0;
6510       for (int i = 0; i < 8; ++i)
6511         if (RepeatedMask[i] >= 16)
6512           BlendMask |= 1u << i;
6513       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6514                          DAG.getConstant(BlendMask, DL, MVT::i8));
6515     }
6516   }
6517     // FALLTHROUGH
6518   case MVT::v16i8:
6519   case MVT::v32i8: {
6520     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6521            "256-bit byte-blends require AVX2 support!");
6522
6523     // Scale the blend by the number of bytes per element.
6524     int Scale = VT.getScalarSizeInBits() / 8;
6525
6526     // This form of blend is always done on bytes. Compute the byte vector
6527     // type.
6528     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6529
6530     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6531     // mix of LLVM's code generator and the x86 backend. We tell the code
6532     // generator that boolean values in the elements of an x86 vector register
6533     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6534     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6535     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6536     // of the element (the remaining are ignored) and 0 in that high bit would
6537     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6538     // the LLVM model for boolean values in vector elements gets the relevant
6539     // bit set, it is set backwards and over constrained relative to x86's
6540     // actual model.
6541     SmallVector<SDValue, 32> VSELECTMask;
6542     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6543       for (int j = 0; j < Scale; ++j)
6544         VSELECTMask.push_back(
6545             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6546                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6547                                           MVT::i8));
6548
6549     V1 = DAG.getBitcast(BlendVT, V1);
6550     V2 = DAG.getBitcast(BlendVT, V2);
6551     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6552                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6553                                                       BlendVT, VSELECTMask),
6554                                           V1, V2));
6555   }
6556
6557   default:
6558     llvm_unreachable("Not a supported integer vector type!");
6559   }
6560 }
6561
6562 /// \brief Try to lower as a blend of elements from two inputs followed by
6563 /// a single-input permutation.
6564 ///
6565 /// This matches the pattern where we can blend elements from two inputs and
6566 /// then reduce the shuffle to a single-input permutation.
6567 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6568                                                    SDValue V2,
6569                                                    ArrayRef<int> Mask,
6570                                                    SelectionDAG &DAG) {
6571   // We build up the blend mask while checking whether a blend is a viable way
6572   // to reduce the shuffle.
6573   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6574   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6575
6576   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6577     if (Mask[i] < 0)
6578       continue;
6579
6580     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6581
6582     if (BlendMask[Mask[i] % Size] == -1)
6583       BlendMask[Mask[i] % Size] = Mask[i];
6584     else if (BlendMask[Mask[i] % Size] != Mask[i])
6585       return SDValue(); // Can't blend in the needed input!
6586
6587     PermuteMask[i] = Mask[i] % Size;
6588   }
6589
6590   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6591   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6592 }
6593
6594 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6595 /// blends and permutes.
6596 ///
6597 /// This matches the extremely common pattern for handling combined
6598 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6599 /// operations. It will try to pick the best arrangement of shuffles and
6600 /// blends.
6601 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6602                                                           SDValue V1,
6603                                                           SDValue V2,
6604                                                           ArrayRef<int> Mask,
6605                                                           SelectionDAG &DAG) {
6606   // Shuffle the input elements into the desired positions in V1 and V2 and
6607   // blend them together.
6608   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6609   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6610   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6611   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6612     if (Mask[i] >= 0 && Mask[i] < Size) {
6613       V1Mask[i] = Mask[i];
6614       BlendMask[i] = i;
6615     } else if (Mask[i] >= Size) {
6616       V2Mask[i] = Mask[i] - Size;
6617       BlendMask[i] = i + Size;
6618     }
6619
6620   // Try to lower with the simpler initial blend strategy unless one of the
6621   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6622   // shuffle may be able to fold with a load or other benefit. However, when
6623   // we'll have to do 2x as many shuffles in order to achieve this, blending
6624   // first is a better strategy.
6625   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6626     if (SDValue BlendPerm =
6627             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6628       return BlendPerm;
6629
6630   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6631   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6632   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6633 }
6634
6635 /// \brief Try to lower a vector shuffle as a byte rotation.
6636 ///
6637 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6638 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6639 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6640 /// try to generically lower a vector shuffle through such an pattern. It
6641 /// does not check for the profitability of lowering either as PALIGNR or
6642 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6643 /// This matches shuffle vectors that look like:
6644 ///
6645 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6646 ///
6647 /// Essentially it concatenates V1 and V2, shifts right by some number of
6648 /// elements, and takes the low elements as the result. Note that while this is
6649 /// specified as a *right shift* because x86 is little-endian, it is a *left
6650 /// rotate* of the vector lanes.
6651 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6652                                               SDValue V2,
6653                                               ArrayRef<int> Mask,
6654                                               const X86Subtarget *Subtarget,
6655                                               SelectionDAG &DAG) {
6656   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6657
6658   int NumElts = Mask.size();
6659   int NumLanes = VT.getSizeInBits() / 128;
6660   int NumLaneElts = NumElts / NumLanes;
6661
6662   // We need to detect various ways of spelling a rotation:
6663   //   [11, 12, 13, 14, 15,  0,  1,  2]
6664   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6665   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6666   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6667   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6668   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6669   int Rotation = 0;
6670   SDValue Lo, Hi;
6671   for (int l = 0; l < NumElts; l += NumLaneElts) {
6672     for (int i = 0; i < NumLaneElts; ++i) {
6673       if (Mask[l + i] == -1)
6674         continue;
6675       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6676
6677       // Get the mod-Size index and lane correct it.
6678       int LaneIdx = (Mask[l + i] % NumElts) - l;
6679       // Make sure it was in this lane.
6680       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6681         return SDValue();
6682
6683       // Determine where a rotated vector would have started.
6684       int StartIdx = i - LaneIdx;
6685       if (StartIdx == 0)
6686         // The identity rotation isn't interesting, stop.
6687         return SDValue();
6688
6689       // If we found the tail of a vector the rotation must be the missing
6690       // front. If we found the head of a vector, it must be how much of the
6691       // head.
6692       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6693
6694       if (Rotation == 0)
6695         Rotation = CandidateRotation;
6696       else if (Rotation != CandidateRotation)
6697         // The rotations don't match, so we can't match this mask.
6698         return SDValue();
6699
6700       // Compute which value this mask is pointing at.
6701       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6702
6703       // Compute which of the two target values this index should be assigned
6704       // to. This reflects whether the high elements are remaining or the low
6705       // elements are remaining.
6706       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6707
6708       // Either set up this value if we've not encountered it before, or check
6709       // that it remains consistent.
6710       if (!TargetV)
6711         TargetV = MaskV;
6712       else if (TargetV != MaskV)
6713         // This may be a rotation, but it pulls from the inputs in some
6714         // unsupported interleaving.
6715         return SDValue();
6716     }
6717   }
6718
6719   // Check that we successfully analyzed the mask, and normalize the results.
6720   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6721   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6722   if (!Lo)
6723     Lo = Hi;
6724   else if (!Hi)
6725     Hi = Lo;
6726
6727   // The actual rotate instruction rotates bytes, so we need to scale the
6728   // rotation based on how many bytes are in the vector lane.
6729   int Scale = 16 / NumLaneElts;
6730
6731   // SSSE3 targets can use the palignr instruction.
6732   if (Subtarget->hasSSSE3()) {
6733     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6734     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6735     Lo = DAG.getBitcast(AlignVT, Lo);
6736     Hi = DAG.getBitcast(AlignVT, Hi);
6737
6738     return DAG.getBitcast(
6739         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6740                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6741   }
6742
6743   assert(VT.getSizeInBits() == 128 &&
6744          "Rotate-based lowering only supports 128-bit lowering!");
6745   assert(Mask.size() <= 16 &&
6746          "Can shuffle at most 16 bytes in a 128-bit vector!");
6747
6748   // Default SSE2 implementation
6749   int LoByteShift = 16 - Rotation * Scale;
6750   int HiByteShift = Rotation * Scale;
6751
6752   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6753   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6754   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6755
6756   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6757                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6758   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6759                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6760   return DAG.getBitcast(VT,
6761                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6762 }
6763
6764 /// \brief Compute whether each element of a shuffle is zeroable.
6765 ///
6766 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6767 /// Either it is an undef element in the shuffle mask, the element of the input
6768 /// referenced is undef, or the element of the input referenced is known to be
6769 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6770 /// as many lanes with this technique as possible to simplify the remaining
6771 /// shuffle.
6772 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6773                                                      SDValue V1, SDValue V2) {
6774   SmallBitVector Zeroable(Mask.size(), false);
6775
6776   while (V1.getOpcode() == ISD::BITCAST)
6777     V1 = V1->getOperand(0);
6778   while (V2.getOpcode() == ISD::BITCAST)
6779     V2 = V2->getOperand(0);
6780
6781   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6782   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6783
6784   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6785     int M = Mask[i];
6786     // Handle the easy cases.
6787     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6788       Zeroable[i] = true;
6789       continue;
6790     }
6791
6792     // If this is an index into a build_vector node (which has the same number
6793     // of elements), dig out the input value and use it.
6794     SDValue V = M < Size ? V1 : V2;
6795     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6796       continue;
6797
6798     SDValue Input = V.getOperand(M % Size);
6799     // The UNDEF opcode check really should be dead code here, but not quite
6800     // worth asserting on (it isn't invalid, just unexpected).
6801     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6802       Zeroable[i] = true;
6803   }
6804
6805   return Zeroable;
6806 }
6807
6808 /// \brief Try to emit a bitmask instruction for a shuffle.
6809 ///
6810 /// This handles cases where we can model a blend exactly as a bitmask due to
6811 /// one of the inputs being zeroable.
6812 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6813                                            SDValue V2, ArrayRef<int> Mask,
6814                                            SelectionDAG &DAG) {
6815   MVT EltVT = VT.getScalarType();
6816   int NumEltBits = EltVT.getSizeInBits();
6817   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6818   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6819   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6820                                     IntEltVT);
6821   if (EltVT.isFloatingPoint()) {
6822     Zero = DAG.getBitcast(EltVT, Zero);
6823     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6824   }
6825   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6826   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6827   SDValue V;
6828   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6829     if (Zeroable[i])
6830       continue;
6831     if (Mask[i] % Size != i)
6832       return SDValue(); // Not a blend.
6833     if (!V)
6834       V = Mask[i] < Size ? V1 : V2;
6835     else if (V != (Mask[i] < Size ? V1 : V2))
6836       return SDValue(); // Can only let one input through the mask.
6837
6838     VMaskOps[i] = AllOnes;
6839   }
6840   if (!V)
6841     return SDValue(); // No non-zeroable elements!
6842
6843   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6844   V = DAG.getNode(VT.isFloatingPoint()
6845                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6846                   DL, VT, V, VMask);
6847   return V;
6848 }
6849
6850 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6851 ///
6852 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6853 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6854 /// matches elements from one of the input vectors shuffled to the left or
6855 /// right with zeroable elements 'shifted in'. It handles both the strictly
6856 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6857 /// quad word lane.
6858 ///
6859 /// PSHL : (little-endian) left bit shift.
6860 /// [ zz, 0, zz,  2 ]
6861 /// [ -1, 4, zz, -1 ]
6862 /// PSRL : (little-endian) right bit shift.
6863 /// [  1, zz,  3, zz]
6864 /// [ -1, -1,  7, zz]
6865 /// PSLLDQ : (little-endian) left byte shift
6866 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6867 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6868 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6869 /// PSRLDQ : (little-endian) right byte shift
6870 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6871 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6872 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6873 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6874                                          SDValue V2, ArrayRef<int> Mask,
6875                                          SelectionDAG &DAG) {
6876   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6877
6878   int Size = Mask.size();
6879   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6880
6881   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6882     for (int i = 0; i < Size; i += Scale)
6883       for (int j = 0; j < Shift; ++j)
6884         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6885           return false;
6886
6887     return true;
6888   };
6889
6890   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6891     for (int i = 0; i != Size; i += Scale) {
6892       unsigned Pos = Left ? i + Shift : i;
6893       unsigned Low = Left ? i : i + Shift;
6894       unsigned Len = Scale - Shift;
6895       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6896                                       Low + (V == V1 ? 0 : Size)))
6897         return SDValue();
6898     }
6899
6900     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6901     bool ByteShift = ShiftEltBits > 64;
6902     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6903                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6904     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6905
6906     // Normalize the scale for byte shifts to still produce an i64 element
6907     // type.
6908     Scale = ByteShift ? Scale / 2 : Scale;
6909
6910     // We need to round trip through the appropriate type for the shift.
6911     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6912     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6913     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6914            "Illegal integer vector type");
6915     V = DAG.getBitcast(ShiftVT, V);
6916
6917     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6918                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6919     return DAG.getBitcast(VT, V);
6920   };
6921
6922   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6923   // keep doubling the size of the integer elements up to that. We can
6924   // then shift the elements of the integer vector by whole multiples of
6925   // their width within the elements of the larger integer vector. Test each
6926   // multiple to see if we can find a match with the moved element indices
6927   // and that the shifted in elements are all zeroable.
6928   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6929     for (int Shift = 1; Shift != Scale; ++Shift)
6930       for (bool Left : {true, false})
6931         if (CheckZeros(Shift, Scale, Left))
6932           for (SDValue V : {V1, V2})
6933             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6934               return Match;
6935
6936   // no match
6937   return SDValue();
6938 }
6939
6940 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6941 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6942                                            SDValue V2, ArrayRef<int> Mask,
6943                                            SelectionDAG &DAG) {
6944   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6945   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6946
6947   int Size = Mask.size();
6948   int HalfSize = Size / 2;
6949   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6950
6951   // Upper half must be undefined.
6952   if (!isUndefInRange(Mask, HalfSize, HalfSize))
6953     return SDValue();
6954
6955   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
6956   // Remainder of lower half result is zero and upper half is all undef.
6957   auto LowerAsEXTRQ = [&]() {
6958     // Determine the extraction length from the part of the
6959     // lower half that isn't zeroable.
6960     int Len = HalfSize;
6961     for (; Len >= 0; --Len)
6962       if (!Zeroable[Len - 1])
6963         break;
6964     assert(Len > 0 && "Zeroable shuffle mask");
6965
6966     // Attempt to match first Len sequential elements from the lower half.
6967     SDValue Src;
6968     int Idx = -1;
6969     for (int i = 0; i != Len; ++i) {
6970       int M = Mask[i];
6971       if (M < 0)
6972         continue;
6973       SDValue &V = (M < Size ? V1 : V2);
6974       M = M % Size;
6975
6976       // All mask elements must be in the lower half.
6977       if (M > HalfSize)
6978         return SDValue();
6979
6980       if (Idx < 0 || (Src == V && Idx == (M - i))) {
6981         Src = V;
6982         Idx = M - i;
6983         continue;
6984       }
6985       return SDValue();
6986     }
6987
6988     if (Idx < 0)
6989       return SDValue();
6990
6991     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
6992     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
6993     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
6994     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
6995                        DAG.getConstant(BitLen, DL, MVT::i8),
6996                        DAG.getConstant(BitIdx, DL, MVT::i8));
6997   };
6998
6999   if (SDValue ExtrQ = LowerAsEXTRQ())
7000     return ExtrQ;
7001
7002   // INSERTQ: Extract lowest Len elements from lower half of second source and
7003   // insert over first source, starting at Idx.
7004   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7005   auto LowerAsInsertQ = [&]() {
7006     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7007       SDValue Base;
7008
7009       // Attempt to match first source from mask before insertion point.
7010       if (isUndefInRange(Mask, 0, Idx)) {
7011         /* EMPTY */
7012       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7013         Base = V1;
7014       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7015         Base = V2;
7016       } else {
7017         continue;
7018       }
7019
7020       // Extend the extraction length looking to match both the insertion of
7021       // the second source and the remaining elements of the first.
7022       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7023         SDValue Insert;
7024         int Len = Hi - Idx;
7025
7026         // Match insertion.
7027         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7028           Insert = V1;
7029         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7030           Insert = V2;
7031         } else {
7032           continue;
7033         }
7034
7035         // Match the remaining elements of the lower half.
7036         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7037           /* EMPTY */
7038         } else if ((!Base || (Base == V1)) &&
7039                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7040           Base = V1;
7041         } else if ((!Base || (Base == V2)) &&
7042                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7043                                               Size + Hi)) {
7044           Base = V2;
7045         } else {
7046           continue;
7047         }
7048
7049         // We may not have a base (first source) - this can safely be undefined.
7050         if (!Base)
7051           Base = DAG.getUNDEF(VT);
7052
7053         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7054         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7055         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7056                            DAG.getConstant(BitLen, DL, MVT::i8),
7057                            DAG.getConstant(BitIdx, DL, MVT::i8));
7058       }
7059     }
7060
7061     return SDValue();
7062   };
7063
7064   if (SDValue InsertQ = LowerAsInsertQ())
7065     return InsertQ;
7066
7067   return SDValue();
7068 }
7069
7070 /// \brief Lower a vector shuffle as a zero or any extension.
7071 ///
7072 /// Given a specific number of elements, element bit width, and extension
7073 /// stride, produce either a zero or any extension based on the available
7074 /// features of the subtarget.
7075 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7076     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7077     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7078   assert(Scale > 1 && "Need a scale to extend.");
7079   int NumElements = VT.getVectorNumElements();
7080   int EltBits = VT.getScalarSizeInBits();
7081   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7082          "Only 8, 16, and 32 bit elements can be extended.");
7083   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7084
7085   // Found a valid zext mask! Try various lowering strategies based on the
7086   // input type and available ISA extensions.
7087   if (Subtarget->hasSSE41()) {
7088     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7089                                  NumElements / Scale);
7090     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7091   }
7092
7093   // For any extends we can cheat for larger element sizes and use shuffle
7094   // instructions that can fold with a load and/or copy.
7095   if (AnyExt && EltBits == 32) {
7096     int PSHUFDMask[4] = {0, -1, 1, -1};
7097     return DAG.getBitcast(
7098         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7099                         DAG.getBitcast(MVT::v4i32, InputV),
7100                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7101   }
7102   if (AnyExt && EltBits == 16 && Scale > 2) {
7103     int PSHUFDMask[4] = {0, -1, 0, -1};
7104     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7105                          DAG.getBitcast(MVT::v4i32, InputV),
7106                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7107     int PSHUFHWMask[4] = {1, -1, -1, -1};
7108     return DAG.getBitcast(
7109         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7110                         DAG.getBitcast(MVT::v8i16, InputV),
7111                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7112   }
7113
7114   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7115   // to 64-bits.
7116   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7117     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7118     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7119
7120     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7121                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7122                                          DAG.getConstant(EltBits, DL, MVT::i8),
7123                                          DAG.getConstant(0, DL, MVT::i8)));
7124     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7125       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7126
7127     SDValue Hi =
7128         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7129                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7130                                 DAG.getConstant(EltBits, DL, MVT::i8),
7131                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7132     return DAG.getNode(ISD::BITCAST, DL, VT,
7133                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7134   }
7135
7136   // If this would require more than 2 unpack instructions to expand, use
7137   // pshufb when available. We can only use more than 2 unpack instructions
7138   // when zero extending i8 elements which also makes it easier to use pshufb.
7139   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7140     assert(NumElements == 16 && "Unexpected byte vector width!");
7141     SDValue PSHUFBMask[16];
7142     for (int i = 0; i < 16; ++i)
7143       PSHUFBMask[i] =
7144           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7145     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7146     return DAG.getBitcast(VT,
7147                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7148                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7149                                                   MVT::v16i8, PSHUFBMask)));
7150   }
7151
7152   // Otherwise emit a sequence of unpacks.
7153   do {
7154     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7155     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7156                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7157     InputV = DAG.getBitcast(InputVT, InputV);
7158     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7159     Scale /= 2;
7160     EltBits *= 2;
7161     NumElements /= 2;
7162   } while (Scale > 1);
7163   return DAG.getBitcast(VT, InputV);
7164 }
7165
7166 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7167 ///
7168 /// This routine will try to do everything in its power to cleverly lower
7169 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7170 /// check for the profitability of this lowering,  it tries to aggressively
7171 /// match this pattern. It will use all of the micro-architectural details it
7172 /// can to emit an efficient lowering. It handles both blends with all-zero
7173 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7174 /// masking out later).
7175 ///
7176 /// The reason we have dedicated lowering for zext-style shuffles is that they
7177 /// are both incredibly common and often quite performance sensitive.
7178 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7179     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7180     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7181   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7182
7183   int Bits = VT.getSizeInBits();
7184   int NumElements = VT.getVectorNumElements();
7185   assert(VT.getScalarSizeInBits() <= 32 &&
7186          "Exceeds 32-bit integer zero extension limit");
7187   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7188
7189   // Define a helper function to check a particular ext-scale and lower to it if
7190   // valid.
7191   auto Lower = [&](int Scale) -> SDValue {
7192     SDValue InputV;
7193     bool AnyExt = true;
7194     for (int i = 0; i < NumElements; ++i) {
7195       if (Mask[i] == -1)
7196         continue; // Valid anywhere but doesn't tell us anything.
7197       if (i % Scale != 0) {
7198         // Each of the extended elements need to be zeroable.
7199         if (!Zeroable[i])
7200           return SDValue();
7201
7202         // We no longer are in the anyext case.
7203         AnyExt = false;
7204         continue;
7205       }
7206
7207       // Each of the base elements needs to be consecutive indices into the
7208       // same input vector.
7209       SDValue V = Mask[i] < NumElements ? V1 : V2;
7210       if (!InputV)
7211         InputV = V;
7212       else if (InputV != V)
7213         return SDValue(); // Flip-flopping inputs.
7214
7215       if (Mask[i] % NumElements != i / Scale)
7216         return SDValue(); // Non-consecutive strided elements.
7217     }
7218
7219     // If we fail to find an input, we have a zero-shuffle which should always
7220     // have already been handled.
7221     // FIXME: Maybe handle this here in case during blending we end up with one?
7222     if (!InputV)
7223       return SDValue();
7224
7225     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7226         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7227   };
7228
7229   // The widest scale possible for extending is to a 64-bit integer.
7230   assert(Bits % 64 == 0 &&
7231          "The number of bits in a vector must be divisible by 64 on x86!");
7232   int NumExtElements = Bits / 64;
7233
7234   // Each iteration, try extending the elements half as much, but into twice as
7235   // many elements.
7236   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7237     assert(NumElements % NumExtElements == 0 &&
7238            "The input vector size must be divisible by the extended size.");
7239     if (SDValue V = Lower(NumElements / NumExtElements))
7240       return V;
7241   }
7242
7243   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7244   if (Bits != 128)
7245     return SDValue();
7246
7247   // Returns one of the source operands if the shuffle can be reduced to a
7248   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7249   auto CanZExtLowHalf = [&]() {
7250     for (int i = NumElements / 2; i != NumElements; ++i)
7251       if (!Zeroable[i])
7252         return SDValue();
7253     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7254       return V1;
7255     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7256       return V2;
7257     return SDValue();
7258   };
7259
7260   if (SDValue V = CanZExtLowHalf()) {
7261     V = DAG.getBitcast(MVT::v2i64, V);
7262     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7263     return DAG.getBitcast(VT, V);
7264   }
7265
7266   // No viable ext lowering found.
7267   return SDValue();
7268 }
7269
7270 /// \brief Try to get a scalar value for a specific element of a vector.
7271 ///
7272 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7273 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7274                                               SelectionDAG &DAG) {
7275   MVT VT = V.getSimpleValueType();
7276   MVT EltVT = VT.getVectorElementType();
7277   while (V.getOpcode() == ISD::BITCAST)
7278     V = V.getOperand(0);
7279   // If the bitcasts shift the element size, we can't extract an equivalent
7280   // element from it.
7281   MVT NewVT = V.getSimpleValueType();
7282   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7283     return SDValue();
7284
7285   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7286       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7287     // Ensure the scalar operand is the same size as the destination.
7288     // FIXME: Add support for scalar truncation where possible.
7289     SDValue S = V.getOperand(Idx);
7290     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7291       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7292   }
7293
7294   return SDValue();
7295 }
7296
7297 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7298 ///
7299 /// This is particularly important because the set of instructions varies
7300 /// significantly based on whether the operand is a load or not.
7301 static bool isShuffleFoldableLoad(SDValue V) {
7302   while (V.getOpcode() == ISD::BITCAST)
7303     V = V.getOperand(0);
7304
7305   return ISD::isNON_EXTLoad(V.getNode());
7306 }
7307
7308 /// \brief Try to lower insertion of a single element into a zero vector.
7309 ///
7310 /// This is a common pattern that we have especially efficient patterns to lower
7311 /// across all subtarget feature sets.
7312 static SDValue lowerVectorShuffleAsElementInsertion(
7313     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7314     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7315   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7316   MVT ExtVT = VT;
7317   MVT EltVT = VT.getVectorElementType();
7318
7319   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7320                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7321                 Mask.begin();
7322   bool IsV1Zeroable = true;
7323   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7324     if (i != V2Index && !Zeroable[i]) {
7325       IsV1Zeroable = false;
7326       break;
7327     }
7328
7329   // Check for a single input from a SCALAR_TO_VECTOR node.
7330   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7331   // all the smarts here sunk into that routine. However, the current
7332   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7333   // vector shuffle lowering is dead.
7334   if (SDValue V2S = getScalarValueForVectorElement(
7335           V2, Mask[V2Index] - Mask.size(), DAG)) {
7336     // We need to zext the scalar if it is smaller than an i32.
7337     V2S = DAG.getBitcast(EltVT, V2S);
7338     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7339       // Using zext to expand a narrow element won't work for non-zero
7340       // insertions.
7341       if (!IsV1Zeroable)
7342         return SDValue();
7343
7344       // Zero-extend directly to i32.
7345       ExtVT = MVT::v4i32;
7346       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7347     }
7348     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7349   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7350              EltVT == MVT::i16) {
7351     // Either not inserting from the low element of the input or the input
7352     // element size is too small to use VZEXT_MOVL to clear the high bits.
7353     return SDValue();
7354   }
7355
7356   if (!IsV1Zeroable) {
7357     // If V1 can't be treated as a zero vector we have fewer options to lower
7358     // this. We can't support integer vectors or non-zero targets cheaply, and
7359     // the V1 elements can't be permuted in any way.
7360     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7361     if (!VT.isFloatingPoint() || V2Index != 0)
7362       return SDValue();
7363     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7364     V1Mask[V2Index] = -1;
7365     if (!isNoopShuffleMask(V1Mask))
7366       return SDValue();
7367     // This is essentially a special case blend operation, but if we have
7368     // general purpose blend operations, they are always faster. Bail and let
7369     // the rest of the lowering handle these as blends.
7370     if (Subtarget->hasSSE41())
7371       return SDValue();
7372
7373     // Otherwise, use MOVSD or MOVSS.
7374     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7375            "Only two types of floating point element types to handle!");
7376     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7377                        ExtVT, V1, V2);
7378   }
7379
7380   // This lowering only works for the low element with floating point vectors.
7381   if (VT.isFloatingPoint() && V2Index != 0)
7382     return SDValue();
7383
7384   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7385   if (ExtVT != VT)
7386     V2 = DAG.getBitcast(VT, V2);
7387
7388   if (V2Index != 0) {
7389     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7390     // the desired position. Otherwise it is more efficient to do a vector
7391     // shift left. We know that we can do a vector shift left because all
7392     // the inputs are zero.
7393     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7394       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7395       V2Shuffle[V2Index] = 0;
7396       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7397     } else {
7398       V2 = DAG.getBitcast(MVT::v2i64, V2);
7399       V2 = DAG.getNode(
7400           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7401           DAG.getConstant(
7402               V2Index * EltVT.getSizeInBits()/8, DL,
7403               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7404       V2 = DAG.getBitcast(VT, V2);
7405     }
7406   }
7407   return V2;
7408 }
7409
7410 /// \brief Try to lower broadcast of a single element.
7411 ///
7412 /// For convenience, this code also bundles all of the subtarget feature set
7413 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7414 /// a convenient way to factor it out.
7415 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7416                                              ArrayRef<int> Mask,
7417                                              const X86Subtarget *Subtarget,
7418                                              SelectionDAG &DAG) {
7419   if (!Subtarget->hasAVX())
7420     return SDValue();
7421   if (VT.isInteger() && !Subtarget->hasAVX2())
7422     return SDValue();
7423
7424   // Check that the mask is a broadcast.
7425   int BroadcastIdx = -1;
7426   for (int M : Mask)
7427     if (M >= 0 && BroadcastIdx == -1)
7428       BroadcastIdx = M;
7429     else if (M >= 0 && M != BroadcastIdx)
7430       return SDValue();
7431
7432   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7433                                             "a sorted mask where the broadcast "
7434                                             "comes from V1.");
7435
7436   // Go up the chain of (vector) values to find a scalar load that we can
7437   // combine with the broadcast.
7438   for (;;) {
7439     switch (V.getOpcode()) {
7440     case ISD::CONCAT_VECTORS: {
7441       int OperandSize = Mask.size() / V.getNumOperands();
7442       V = V.getOperand(BroadcastIdx / OperandSize);
7443       BroadcastIdx %= OperandSize;
7444       continue;
7445     }
7446
7447     case ISD::INSERT_SUBVECTOR: {
7448       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7449       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7450       if (!ConstantIdx)
7451         break;
7452
7453       int BeginIdx = (int)ConstantIdx->getZExtValue();
7454       int EndIdx =
7455           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7456       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7457         BroadcastIdx -= BeginIdx;
7458         V = VInner;
7459       } else {
7460         V = VOuter;
7461       }
7462       continue;
7463     }
7464     }
7465     break;
7466   }
7467
7468   // Check if this is a broadcast of a scalar. We special case lowering
7469   // for scalars so that we can more effectively fold with loads.
7470   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7471       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7472     V = V.getOperand(BroadcastIdx);
7473
7474     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7475     // Only AVX2 has register broadcasts.
7476     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7477       return SDValue();
7478   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7479     // We can't broadcast from a vector register without AVX2, and we can only
7480     // broadcast from the zero-element of a vector register.
7481     return SDValue();
7482   }
7483
7484   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7485 }
7486
7487 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7488 // INSERTPS when the V1 elements are already in the correct locations
7489 // because otherwise we can just always use two SHUFPS instructions which
7490 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7491 // perform INSERTPS if a single V1 element is out of place and all V2
7492 // elements are zeroable.
7493 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7494                                             ArrayRef<int> Mask,
7495                                             SelectionDAG &DAG) {
7496   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7497   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7498   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7499   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7500
7501   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7502
7503   unsigned ZMask = 0;
7504   int V1DstIndex = -1;
7505   int V2DstIndex = -1;
7506   bool V1UsedInPlace = false;
7507
7508   for (int i = 0; i < 4; ++i) {
7509     // Synthesize a zero mask from the zeroable elements (includes undefs).
7510     if (Zeroable[i]) {
7511       ZMask |= 1 << i;
7512       continue;
7513     }
7514
7515     // Flag if we use any V1 inputs in place.
7516     if (i == Mask[i]) {
7517       V1UsedInPlace = true;
7518       continue;
7519     }
7520
7521     // We can only insert a single non-zeroable element.
7522     if (V1DstIndex != -1 || V2DstIndex != -1)
7523       return SDValue();
7524
7525     if (Mask[i] < 4) {
7526       // V1 input out of place for insertion.
7527       V1DstIndex = i;
7528     } else {
7529       // V2 input for insertion.
7530       V2DstIndex = i;
7531     }
7532   }
7533
7534   // Don't bother if we have no (non-zeroable) element for insertion.
7535   if (V1DstIndex == -1 && V2DstIndex == -1)
7536     return SDValue();
7537
7538   // Determine element insertion src/dst indices. The src index is from the
7539   // start of the inserted vector, not the start of the concatenated vector.
7540   unsigned V2SrcIndex = 0;
7541   if (V1DstIndex != -1) {
7542     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7543     // and don't use the original V2 at all.
7544     V2SrcIndex = Mask[V1DstIndex];
7545     V2DstIndex = V1DstIndex;
7546     V2 = V1;
7547   } else {
7548     V2SrcIndex = Mask[V2DstIndex] - 4;
7549   }
7550
7551   // If no V1 inputs are used in place, then the result is created only from
7552   // the zero mask and the V2 insertion - so remove V1 dependency.
7553   if (!V1UsedInPlace)
7554     V1 = DAG.getUNDEF(MVT::v4f32);
7555
7556   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7557   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7558
7559   // Insert the V2 element into the desired position.
7560   SDLoc DL(Op);
7561   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7562                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7563 }
7564
7565 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7566 /// UNPCK instruction.
7567 ///
7568 /// This specifically targets cases where we end up with alternating between
7569 /// the two inputs, and so can permute them into something that feeds a single
7570 /// UNPCK instruction. Note that this routine only targets integer vectors
7571 /// because for floating point vectors we have a generalized SHUFPS lowering
7572 /// strategy that handles everything that doesn't *exactly* match an unpack,
7573 /// making this clever lowering unnecessary.
7574 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7575                                           SDValue V2, ArrayRef<int> Mask,
7576                                           SelectionDAG &DAG) {
7577   assert(!VT.isFloatingPoint() &&
7578          "This routine only supports integer vectors.");
7579   assert(!isSingleInputShuffleMask(Mask) &&
7580          "This routine should only be used when blending two inputs.");
7581   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7582
7583   int Size = Mask.size();
7584
7585   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7586     return M >= 0 && M % Size < Size / 2;
7587   });
7588   int NumHiInputs = std::count_if(
7589       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7590
7591   bool UnpackLo = NumLoInputs >= NumHiInputs;
7592
7593   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7594     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7595     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7596
7597     for (int i = 0; i < Size; ++i) {
7598       if (Mask[i] < 0)
7599         continue;
7600
7601       // Each element of the unpack contains Scale elements from this mask.
7602       int UnpackIdx = i / Scale;
7603
7604       // We only handle the case where V1 feeds the first slots of the unpack.
7605       // We rely on canonicalization to ensure this is the case.
7606       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7607         return SDValue();
7608
7609       // Setup the mask for this input. The indexing is tricky as we have to
7610       // handle the unpack stride.
7611       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7612       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7613           Mask[i] % Size;
7614     }
7615
7616     // If we will have to shuffle both inputs to use the unpack, check whether
7617     // we can just unpack first and shuffle the result. If so, skip this unpack.
7618     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7619         !isNoopShuffleMask(V2Mask))
7620       return SDValue();
7621
7622     // Shuffle the inputs into place.
7623     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7624     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7625
7626     // Cast the inputs to the type we will use to unpack them.
7627     V1 = DAG.getBitcast(UnpackVT, V1);
7628     V2 = DAG.getBitcast(UnpackVT, V2);
7629
7630     // Unpack the inputs and cast the result back to the desired type.
7631     return DAG.getBitcast(
7632         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7633                         UnpackVT, V1, V2));
7634   };
7635
7636   // We try each unpack from the largest to the smallest to try and find one
7637   // that fits this mask.
7638   int OrigNumElements = VT.getVectorNumElements();
7639   int OrigScalarSize = VT.getScalarSizeInBits();
7640   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7641     int Scale = ScalarSize / OrigScalarSize;
7642     int NumElements = OrigNumElements / Scale;
7643     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7644     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7645       return Unpack;
7646   }
7647
7648   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7649   // initial unpack.
7650   if (NumLoInputs == 0 || NumHiInputs == 0) {
7651     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7652            "We have to have *some* inputs!");
7653     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7654
7655     // FIXME: We could consider the total complexity of the permute of each
7656     // possible unpacking. Or at the least we should consider how many
7657     // half-crossings are created.
7658     // FIXME: We could consider commuting the unpacks.
7659
7660     SmallVector<int, 32> PermMask;
7661     PermMask.assign(Size, -1);
7662     for (int i = 0; i < Size; ++i) {
7663       if (Mask[i] < 0)
7664         continue;
7665
7666       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7667
7668       PermMask[i] =
7669           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7670     }
7671     return DAG.getVectorShuffle(
7672         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7673                             DL, VT, V1, V2),
7674         DAG.getUNDEF(VT), PermMask);
7675   }
7676
7677   return SDValue();
7678 }
7679
7680 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7681 ///
7682 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7683 /// support for floating point shuffles but not integer shuffles. These
7684 /// instructions will incur a domain crossing penalty on some chips though so
7685 /// it is better to avoid lowering through this for integer vectors where
7686 /// possible.
7687 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7688                                        const X86Subtarget *Subtarget,
7689                                        SelectionDAG &DAG) {
7690   SDLoc DL(Op);
7691   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7692   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7693   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7694   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7695   ArrayRef<int> Mask = SVOp->getMask();
7696   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7697
7698   if (isSingleInputShuffleMask(Mask)) {
7699     // Use low duplicate instructions for masks that match their pattern.
7700     if (Subtarget->hasSSE3())
7701       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7702         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7703
7704     // Straight shuffle of a single input vector. Simulate this by using the
7705     // single input as both of the "inputs" to this instruction..
7706     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7707
7708     if (Subtarget->hasAVX()) {
7709       // If we have AVX, we can use VPERMILPS which will allow folding a load
7710       // into the shuffle.
7711       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7712                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7713     }
7714
7715     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7716                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7717   }
7718   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7719   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7720
7721   // If we have a single input, insert that into V1 if we can do so cheaply.
7722   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7723     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7724             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7725       return Insertion;
7726     // Try inverting the insertion since for v2 masks it is easy to do and we
7727     // can't reliably sort the mask one way or the other.
7728     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7729                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7730     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7731             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7732       return Insertion;
7733   }
7734
7735   // Try to use one of the special instruction patterns to handle two common
7736   // blend patterns if a zero-blend above didn't work.
7737   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7738       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7739     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7740       // We can either use a special instruction to load over the low double or
7741       // to move just the low double.
7742       return DAG.getNode(
7743           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7744           DL, MVT::v2f64, V2,
7745           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7746
7747   if (Subtarget->hasSSE41())
7748     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7749                                                   Subtarget, DAG))
7750       return Blend;
7751
7752   // Use dedicated unpack instructions for masks that match their pattern.
7753   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7754     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7755   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7756     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7757
7758   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7759   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7760                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7761 }
7762
7763 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7764 ///
7765 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7766 /// the integer unit to minimize domain crossing penalties. However, for blends
7767 /// it falls back to the floating point shuffle operation with appropriate bit
7768 /// casting.
7769 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7770                                        const X86Subtarget *Subtarget,
7771                                        SelectionDAG &DAG) {
7772   SDLoc DL(Op);
7773   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7774   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7775   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7776   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7777   ArrayRef<int> Mask = SVOp->getMask();
7778   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7779
7780   if (isSingleInputShuffleMask(Mask)) {
7781     // Check for being able to broadcast a single element.
7782     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7783                                                           Mask, Subtarget, DAG))
7784       return Broadcast;
7785
7786     // Straight shuffle of a single input vector. For everything from SSE2
7787     // onward this has a single fast instruction with no scary immediates.
7788     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7789     V1 = DAG.getBitcast(MVT::v4i32, V1);
7790     int WidenedMask[4] = {
7791         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7792         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7793     return DAG.getBitcast(
7794         MVT::v2i64,
7795         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7796                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7797   }
7798   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7799   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7800   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7801   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7802
7803   // If we have a blend of two PACKUS operations an the blend aligns with the
7804   // low and half halves, we can just merge the PACKUS operations. This is
7805   // particularly important as it lets us merge shuffles that this routine itself
7806   // creates.
7807   auto GetPackNode = [](SDValue V) {
7808     while (V.getOpcode() == ISD::BITCAST)
7809       V = V.getOperand(0);
7810
7811     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7812   };
7813   if (SDValue V1Pack = GetPackNode(V1))
7814     if (SDValue V2Pack = GetPackNode(V2))
7815       return DAG.getBitcast(MVT::v2i64,
7816                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7817                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7818                                                      : V1Pack.getOperand(1),
7819                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7820                                                      : V2Pack.getOperand(1)));
7821
7822   // Try to use shift instructions.
7823   if (SDValue Shift =
7824           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7825     return Shift;
7826
7827   // When loading a scalar and then shuffling it into a vector we can often do
7828   // the insertion cheaply.
7829   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7830           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7831     return Insertion;
7832   // Try inverting the insertion since for v2 masks it is easy to do and we
7833   // can't reliably sort the mask one way or the other.
7834   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7835   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7836           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7837     return Insertion;
7838
7839   // We have different paths for blend lowering, but they all must use the
7840   // *exact* same predicate.
7841   bool IsBlendSupported = Subtarget->hasSSE41();
7842   if (IsBlendSupported)
7843     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7844                                                   Subtarget, DAG))
7845       return Blend;
7846
7847   // Use dedicated unpack instructions for masks that match their pattern.
7848   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7849     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7850   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7851     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7852
7853   // Try to use byte rotation instructions.
7854   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7855   if (Subtarget->hasSSSE3())
7856     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7857             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7858       return Rotate;
7859
7860   // If we have direct support for blends, we should lower by decomposing into
7861   // a permute. That will be faster than the domain cross.
7862   if (IsBlendSupported)
7863     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7864                                                       Mask, DAG);
7865
7866   // We implement this with SHUFPD which is pretty lame because it will likely
7867   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7868   // However, all the alternatives are still more cycles and newer chips don't
7869   // have this problem. It would be really nice if x86 had better shuffles here.
7870   V1 = DAG.getBitcast(MVT::v2f64, V1);
7871   V2 = DAG.getBitcast(MVT::v2f64, V2);
7872   return DAG.getBitcast(MVT::v2i64,
7873                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7874 }
7875
7876 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7877 ///
7878 /// This is used to disable more specialized lowerings when the shufps lowering
7879 /// will happen to be efficient.
7880 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7881   // This routine only handles 128-bit shufps.
7882   assert(Mask.size() == 4 && "Unsupported mask size!");
7883
7884   // To lower with a single SHUFPS we need to have the low half and high half
7885   // each requiring a single input.
7886   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7887     return false;
7888   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7889     return false;
7890
7891   return true;
7892 }
7893
7894 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7895 ///
7896 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7897 /// It makes no assumptions about whether this is the *best* lowering, it simply
7898 /// uses it.
7899 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7900                                             ArrayRef<int> Mask, SDValue V1,
7901                                             SDValue V2, SelectionDAG &DAG) {
7902   SDValue LowV = V1, HighV = V2;
7903   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7904
7905   int NumV2Elements =
7906       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7907
7908   if (NumV2Elements == 1) {
7909     int V2Index =
7910         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7911         Mask.begin();
7912
7913     // Compute the index adjacent to V2Index and in the same half by toggling
7914     // the low bit.
7915     int V2AdjIndex = V2Index ^ 1;
7916
7917     if (Mask[V2AdjIndex] == -1) {
7918       // Handles all the cases where we have a single V2 element and an undef.
7919       // This will only ever happen in the high lanes because we commute the
7920       // vector otherwise.
7921       if (V2Index < 2)
7922         std::swap(LowV, HighV);
7923       NewMask[V2Index] -= 4;
7924     } else {
7925       // Handle the case where the V2 element ends up adjacent to a V1 element.
7926       // To make this work, blend them together as the first step.
7927       int V1Index = V2AdjIndex;
7928       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7929       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7930                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7931
7932       // Now proceed to reconstruct the final blend as we have the necessary
7933       // high or low half formed.
7934       if (V2Index < 2) {
7935         LowV = V2;
7936         HighV = V1;
7937       } else {
7938         HighV = V2;
7939       }
7940       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7941       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7942     }
7943   } else if (NumV2Elements == 2) {
7944     if (Mask[0] < 4 && Mask[1] < 4) {
7945       // Handle the easy case where we have V1 in the low lanes and V2 in the
7946       // high lanes.
7947       NewMask[2] -= 4;
7948       NewMask[3] -= 4;
7949     } else if (Mask[2] < 4 && Mask[3] < 4) {
7950       // We also handle the reversed case because this utility may get called
7951       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7952       // arrange things in the right direction.
7953       NewMask[0] -= 4;
7954       NewMask[1] -= 4;
7955       HighV = V1;
7956       LowV = V2;
7957     } else {
7958       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7959       // trying to place elements directly, just blend them and set up the final
7960       // shuffle to place them.
7961
7962       // The first two blend mask elements are for V1, the second two are for
7963       // V2.
7964       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7965                           Mask[2] < 4 ? Mask[2] : Mask[3],
7966                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7967                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7968       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7969                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7970
7971       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7972       // a blend.
7973       LowV = HighV = V1;
7974       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7975       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7976       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7977       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7978     }
7979   }
7980   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7981                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7982 }
7983
7984 /// \brief Lower 4-lane 32-bit floating point shuffles.
7985 ///
7986 /// Uses instructions exclusively from the floating point unit to minimize
7987 /// domain crossing penalties, as these are sufficient to implement all v4f32
7988 /// shuffles.
7989 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7990                                        const X86Subtarget *Subtarget,
7991                                        SelectionDAG &DAG) {
7992   SDLoc DL(Op);
7993   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7994   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7995   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7996   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7997   ArrayRef<int> Mask = SVOp->getMask();
7998   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7999
8000   int NumV2Elements =
8001       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8002
8003   if (NumV2Elements == 0) {
8004     // Check for being able to broadcast a single element.
8005     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8006                                                           Mask, Subtarget, DAG))
8007       return Broadcast;
8008
8009     // Use even/odd duplicate instructions for masks that match their pattern.
8010     if (Subtarget->hasSSE3()) {
8011       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8012         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8013       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8014         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8015     }
8016
8017     if (Subtarget->hasAVX()) {
8018       // If we have AVX, we can use VPERMILPS which will allow folding a load
8019       // into the shuffle.
8020       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8021                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8022     }
8023
8024     // Otherwise, use a straight shuffle of a single input vector. We pass the
8025     // input vector to both operands to simulate this with a SHUFPS.
8026     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8027                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8028   }
8029
8030   // There are special ways we can lower some single-element blends. However, we
8031   // have custom ways we can lower more complex single-element blends below that
8032   // we defer to if both this and BLENDPS fail to match, so restrict this to
8033   // when the V2 input is targeting element 0 of the mask -- that is the fast
8034   // case here.
8035   if (NumV2Elements == 1 && Mask[0] >= 4)
8036     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8037                                                          Mask, Subtarget, DAG))
8038       return V;
8039
8040   if (Subtarget->hasSSE41()) {
8041     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8042                                                   Subtarget, DAG))
8043       return Blend;
8044
8045     // Use INSERTPS if we can complete the shuffle efficiently.
8046     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8047       return V;
8048
8049     if (!isSingleSHUFPSMask(Mask))
8050       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8051               DL, MVT::v4f32, V1, V2, Mask, DAG))
8052         return BlendPerm;
8053   }
8054
8055   // Use dedicated unpack instructions for masks that match their pattern.
8056   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8057     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8058   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8059     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8060   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8061     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8062   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8063     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8064
8065   // Otherwise fall back to a SHUFPS lowering strategy.
8066   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8067 }
8068
8069 /// \brief Lower 4-lane i32 vector shuffles.
8070 ///
8071 /// We try to handle these with integer-domain shuffles where we can, but for
8072 /// blends we use the floating point domain blend instructions.
8073 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8074                                        const X86Subtarget *Subtarget,
8075                                        SelectionDAG &DAG) {
8076   SDLoc DL(Op);
8077   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8078   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8079   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8080   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8081   ArrayRef<int> Mask = SVOp->getMask();
8082   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8083
8084   // Whenever we can lower this as a zext, that instruction is strictly faster
8085   // than any alternative. It also allows us to fold memory operands into the
8086   // shuffle in many cases.
8087   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8088                                                          Mask, Subtarget, DAG))
8089     return ZExt;
8090
8091   int NumV2Elements =
8092       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8093
8094   if (NumV2Elements == 0) {
8095     // Check for being able to broadcast a single element.
8096     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8097                                                           Mask, Subtarget, DAG))
8098       return Broadcast;
8099
8100     // Straight shuffle of a single input vector. For everything from SSE2
8101     // onward this has a single fast instruction with no scary immediates.
8102     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8103     // but we aren't actually going to use the UNPCK instruction because doing
8104     // so prevents folding a load into this instruction or making a copy.
8105     const int UnpackLoMask[] = {0, 0, 1, 1};
8106     const int UnpackHiMask[] = {2, 2, 3, 3};
8107     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8108       Mask = UnpackLoMask;
8109     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8110       Mask = UnpackHiMask;
8111
8112     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8113                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8114   }
8115
8116   // Try to use shift instructions.
8117   if (SDValue Shift =
8118           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8119     return Shift;
8120
8121   // There are special ways we can lower some single-element blends.
8122   if (NumV2Elements == 1)
8123     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8124                                                          Mask, Subtarget, DAG))
8125       return V;
8126
8127   // We have different paths for blend lowering, but they all must use the
8128   // *exact* same predicate.
8129   bool IsBlendSupported = Subtarget->hasSSE41();
8130   if (IsBlendSupported)
8131     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8132                                                   Subtarget, DAG))
8133       return Blend;
8134
8135   if (SDValue Masked =
8136           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8137     return Masked;
8138
8139   // Use dedicated unpack instructions for masks that match their pattern.
8140   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8141     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8142   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8143     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8144   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8145     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8146   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8147     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8148
8149   // Try to use byte rotation instructions.
8150   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8151   if (Subtarget->hasSSSE3())
8152     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8153             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8154       return Rotate;
8155
8156   // If we have direct support for blends, we should lower by decomposing into
8157   // a permute. That will be faster than the domain cross.
8158   if (IsBlendSupported)
8159     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8160                                                       Mask, DAG);
8161
8162   // Try to lower by permuting the inputs into an unpack instruction.
8163   if (SDValue Unpack =
8164           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8165     return Unpack;
8166
8167   // We implement this with SHUFPS because it can blend from two vectors.
8168   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8169   // up the inputs, bypassing domain shift penalties that we would encur if we
8170   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8171   // relevant.
8172   return DAG.getBitcast(
8173       MVT::v4i32,
8174       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8175                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8176 }
8177
8178 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8179 /// shuffle lowering, and the most complex part.
8180 ///
8181 /// The lowering strategy is to try to form pairs of input lanes which are
8182 /// targeted at the same half of the final vector, and then use a dword shuffle
8183 /// to place them onto the right half, and finally unpack the paired lanes into
8184 /// their final position.
8185 ///
8186 /// The exact breakdown of how to form these dword pairs and align them on the
8187 /// correct sides is really tricky. See the comments within the function for
8188 /// more of the details.
8189 ///
8190 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8191 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8192 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8193 /// vector, form the analogous 128-bit 8-element Mask.
8194 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8195     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8196     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8197   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8198   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8199
8200   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8201   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8202   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8203
8204   SmallVector<int, 4> LoInputs;
8205   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8206                [](int M) { return M >= 0; });
8207   std::sort(LoInputs.begin(), LoInputs.end());
8208   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8209   SmallVector<int, 4> HiInputs;
8210   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8211                [](int M) { return M >= 0; });
8212   std::sort(HiInputs.begin(), HiInputs.end());
8213   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8214   int NumLToL =
8215       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8216   int NumHToL = LoInputs.size() - NumLToL;
8217   int NumLToH =
8218       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8219   int NumHToH = HiInputs.size() - NumLToH;
8220   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8221   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8222   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8223   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8224
8225   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8226   // such inputs we can swap two of the dwords across the half mark and end up
8227   // with <=2 inputs to each half in each half. Once there, we can fall through
8228   // to the generic code below. For example:
8229   //
8230   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8231   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8232   //
8233   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8234   // and an existing 2-into-2 on the other half. In this case we may have to
8235   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8236   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8237   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8238   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8239   // half than the one we target for fixing) will be fixed when we re-enter this
8240   // path. We will also combine away any sequence of PSHUFD instructions that
8241   // result into a single instruction. Here is an example of the tricky case:
8242   //
8243   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8244   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8245   //
8246   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8247   //
8248   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8249   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8250   //
8251   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8252   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8253   //
8254   // The result is fine to be handled by the generic logic.
8255   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8256                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8257                           int AOffset, int BOffset) {
8258     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8259            "Must call this with A having 3 or 1 inputs from the A half.");
8260     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8261            "Must call this with B having 1 or 3 inputs from the B half.");
8262     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8263            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8264
8265     // Compute the index of dword with only one word among the three inputs in
8266     // a half by taking the sum of the half with three inputs and subtracting
8267     // the sum of the actual three inputs. The difference is the remaining
8268     // slot.
8269     int ADWord, BDWord;
8270     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8271     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8272     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8273     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8274     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8275     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8276     int TripleNonInputIdx =
8277         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8278     TripleDWord = TripleNonInputIdx / 2;
8279
8280     // We use xor with one to compute the adjacent DWord to whichever one the
8281     // OneInput is in.
8282     OneInputDWord = (OneInput / 2) ^ 1;
8283
8284     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8285     // and BToA inputs. If there is also such a problem with the BToB and AToB
8286     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8287     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8288     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8289     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8290       // Compute how many inputs will be flipped by swapping these DWords. We
8291       // need
8292       // to balance this to ensure we don't form a 3-1 shuffle in the other
8293       // half.
8294       int NumFlippedAToBInputs =
8295           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8296           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8297       int NumFlippedBToBInputs =
8298           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8299           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8300       if ((NumFlippedAToBInputs == 1 &&
8301            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8302           (NumFlippedBToBInputs == 1 &&
8303            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8304         // We choose whether to fix the A half or B half based on whether that
8305         // half has zero flipped inputs. At zero, we may not be able to fix it
8306         // with that half. We also bias towards fixing the B half because that
8307         // will more commonly be the high half, and we have to bias one way.
8308         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8309                                                        ArrayRef<int> Inputs) {
8310           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8311           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8312                                          PinnedIdx ^ 1) != Inputs.end();
8313           // Determine whether the free index is in the flipped dword or the
8314           // unflipped dword based on where the pinned index is. We use this bit
8315           // in an xor to conditionally select the adjacent dword.
8316           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8317           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8318                                              FixFreeIdx) != Inputs.end();
8319           if (IsFixIdxInput == IsFixFreeIdxInput)
8320             FixFreeIdx += 1;
8321           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8322                                         FixFreeIdx) != Inputs.end();
8323           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8324                  "We need to be changing the number of flipped inputs!");
8325           int PSHUFHalfMask[] = {0, 1, 2, 3};
8326           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8327           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8328                           MVT::v8i16, V,
8329                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8330
8331           for (int &M : Mask)
8332             if (M != -1 && M == FixIdx)
8333               M = FixFreeIdx;
8334             else if (M != -1 && M == FixFreeIdx)
8335               M = FixIdx;
8336         };
8337         if (NumFlippedBToBInputs != 0) {
8338           int BPinnedIdx =
8339               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8340           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8341         } else {
8342           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8343           int APinnedIdx =
8344               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8345           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8346         }
8347       }
8348     }
8349
8350     int PSHUFDMask[] = {0, 1, 2, 3};
8351     PSHUFDMask[ADWord] = BDWord;
8352     PSHUFDMask[BDWord] = ADWord;
8353     V = DAG.getBitcast(
8354         VT,
8355         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8356                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8357
8358     // Adjust the mask to match the new locations of A and B.
8359     for (int &M : Mask)
8360       if (M != -1 && M/2 == ADWord)
8361         M = 2 * BDWord + M % 2;
8362       else if (M != -1 && M/2 == BDWord)
8363         M = 2 * ADWord + M % 2;
8364
8365     // Recurse back into this routine to re-compute state now that this isn't
8366     // a 3 and 1 problem.
8367     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8368                                                      DAG);
8369   };
8370   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8371     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8372   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8373     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8374
8375   // At this point there are at most two inputs to the low and high halves from
8376   // each half. That means the inputs can always be grouped into dwords and
8377   // those dwords can then be moved to the correct half with a dword shuffle.
8378   // We use at most one low and one high word shuffle to collect these paired
8379   // inputs into dwords, and finally a dword shuffle to place them.
8380   int PSHUFLMask[4] = {-1, -1, -1, -1};
8381   int PSHUFHMask[4] = {-1, -1, -1, -1};
8382   int PSHUFDMask[4] = {-1, -1, -1, -1};
8383
8384   // First fix the masks for all the inputs that are staying in their
8385   // original halves. This will then dictate the targets of the cross-half
8386   // shuffles.
8387   auto fixInPlaceInputs =
8388       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8389                     MutableArrayRef<int> SourceHalfMask,
8390                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8391     if (InPlaceInputs.empty())
8392       return;
8393     if (InPlaceInputs.size() == 1) {
8394       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8395           InPlaceInputs[0] - HalfOffset;
8396       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8397       return;
8398     }
8399     if (IncomingInputs.empty()) {
8400       // Just fix all of the in place inputs.
8401       for (int Input : InPlaceInputs) {
8402         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8403         PSHUFDMask[Input / 2] = Input / 2;
8404       }
8405       return;
8406     }
8407
8408     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8409     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8410         InPlaceInputs[0] - HalfOffset;
8411     // Put the second input next to the first so that they are packed into
8412     // a dword. We find the adjacent index by toggling the low bit.
8413     int AdjIndex = InPlaceInputs[0] ^ 1;
8414     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8415     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8416     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8417   };
8418   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8419   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8420
8421   // Now gather the cross-half inputs and place them into a free dword of
8422   // their target half.
8423   // FIXME: This operation could almost certainly be simplified dramatically to
8424   // look more like the 3-1 fixing operation.
8425   auto moveInputsToRightHalf = [&PSHUFDMask](
8426       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8427       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8428       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8429       int DestOffset) {
8430     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8431       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8432     };
8433     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8434                                                int Word) {
8435       int LowWord = Word & ~1;
8436       int HighWord = Word | 1;
8437       return isWordClobbered(SourceHalfMask, LowWord) ||
8438              isWordClobbered(SourceHalfMask, HighWord);
8439     };
8440
8441     if (IncomingInputs.empty())
8442       return;
8443
8444     if (ExistingInputs.empty()) {
8445       // Map any dwords with inputs from them into the right half.
8446       for (int Input : IncomingInputs) {
8447         // If the source half mask maps over the inputs, turn those into
8448         // swaps and use the swapped lane.
8449         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8450           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8451             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8452                 Input - SourceOffset;
8453             // We have to swap the uses in our half mask in one sweep.
8454             for (int &M : HalfMask)
8455               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8456                 M = Input;
8457               else if (M == Input)
8458                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8459           } else {
8460             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8461                        Input - SourceOffset &&
8462                    "Previous placement doesn't match!");
8463           }
8464           // Note that this correctly re-maps both when we do a swap and when
8465           // we observe the other side of the swap above. We rely on that to
8466           // avoid swapping the members of the input list directly.
8467           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8468         }
8469
8470         // Map the input's dword into the correct half.
8471         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8472           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8473         else
8474           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8475                      Input / 2 &&
8476                  "Previous placement doesn't match!");
8477       }
8478
8479       // And just directly shift any other-half mask elements to be same-half
8480       // as we will have mirrored the dword containing the element into the
8481       // same position within that half.
8482       for (int &M : HalfMask)
8483         if (M >= SourceOffset && M < SourceOffset + 4) {
8484           M = M - SourceOffset + DestOffset;
8485           assert(M >= 0 && "This should never wrap below zero!");
8486         }
8487       return;
8488     }
8489
8490     // Ensure we have the input in a viable dword of its current half. This
8491     // is particularly tricky because the original position may be clobbered
8492     // by inputs being moved and *staying* in that half.
8493     if (IncomingInputs.size() == 1) {
8494       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8495         int InputFixed = std::find(std::begin(SourceHalfMask),
8496                                    std::end(SourceHalfMask), -1) -
8497                          std::begin(SourceHalfMask) + SourceOffset;
8498         SourceHalfMask[InputFixed - SourceOffset] =
8499             IncomingInputs[0] - SourceOffset;
8500         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8501                      InputFixed);
8502         IncomingInputs[0] = InputFixed;
8503       }
8504     } else if (IncomingInputs.size() == 2) {
8505       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8506           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8507         // We have two non-adjacent or clobbered inputs we need to extract from
8508         // the source half. To do this, we need to map them into some adjacent
8509         // dword slot in the source mask.
8510         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8511                               IncomingInputs[1] - SourceOffset};
8512
8513         // If there is a free slot in the source half mask adjacent to one of
8514         // the inputs, place the other input in it. We use (Index XOR 1) to
8515         // compute an adjacent index.
8516         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8517             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8518           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8519           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8520           InputsFixed[1] = InputsFixed[0] ^ 1;
8521         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8522                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8523           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8524           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8525           InputsFixed[0] = InputsFixed[1] ^ 1;
8526         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8527                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8528           // The two inputs are in the same DWord but it is clobbered and the
8529           // adjacent DWord isn't used at all. Move both inputs to the free
8530           // slot.
8531           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8532           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8533           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8534           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8535         } else {
8536           // The only way we hit this point is if there is no clobbering
8537           // (because there are no off-half inputs to this half) and there is no
8538           // free slot adjacent to one of the inputs. In this case, we have to
8539           // swap an input with a non-input.
8540           for (int i = 0; i < 4; ++i)
8541             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8542                    "We can't handle any clobbers here!");
8543           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8544                  "Cannot have adjacent inputs here!");
8545
8546           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8547           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8548
8549           // We also have to update the final source mask in this case because
8550           // it may need to undo the above swap.
8551           for (int &M : FinalSourceHalfMask)
8552             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8553               M = InputsFixed[1] + SourceOffset;
8554             else if (M == InputsFixed[1] + SourceOffset)
8555               M = (InputsFixed[0] ^ 1) + SourceOffset;
8556
8557           InputsFixed[1] = InputsFixed[0] ^ 1;
8558         }
8559
8560         // Point everything at the fixed inputs.
8561         for (int &M : HalfMask)
8562           if (M == IncomingInputs[0])
8563             M = InputsFixed[0] + SourceOffset;
8564           else if (M == IncomingInputs[1])
8565             M = InputsFixed[1] + SourceOffset;
8566
8567         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8568         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8569       }
8570     } else {
8571       llvm_unreachable("Unhandled input size!");
8572     }
8573
8574     // Now hoist the DWord down to the right half.
8575     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8576     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8577     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8578     for (int &M : HalfMask)
8579       for (int Input : IncomingInputs)
8580         if (M == Input)
8581           M = FreeDWord * 2 + Input % 2;
8582   };
8583   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8584                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8585   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8586                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8587
8588   // Now enact all the shuffles we've computed to move the inputs into their
8589   // target half.
8590   if (!isNoopShuffleMask(PSHUFLMask))
8591     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8592                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8593   if (!isNoopShuffleMask(PSHUFHMask))
8594     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8595                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8596   if (!isNoopShuffleMask(PSHUFDMask))
8597     V = DAG.getBitcast(
8598         VT,
8599         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8600                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8601
8602   // At this point, each half should contain all its inputs, and we can then
8603   // just shuffle them into their final position.
8604   assert(std::count_if(LoMask.begin(), LoMask.end(),
8605                        [](int M) { return M >= 4; }) == 0 &&
8606          "Failed to lift all the high half inputs to the low mask!");
8607   assert(std::count_if(HiMask.begin(), HiMask.end(),
8608                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8609          "Failed to lift all the low half inputs to the high mask!");
8610
8611   // Do a half shuffle for the low mask.
8612   if (!isNoopShuffleMask(LoMask))
8613     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8614                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8615
8616   // Do a half shuffle with the high mask after shifting its values down.
8617   for (int &M : HiMask)
8618     if (M >= 0)
8619       M -= 4;
8620   if (!isNoopShuffleMask(HiMask))
8621     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8622                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8623
8624   return V;
8625 }
8626
8627 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8628 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8629                                           SDValue V2, ArrayRef<int> Mask,
8630                                           SelectionDAG &DAG, bool &V1InUse,
8631                                           bool &V2InUse) {
8632   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8633   SDValue V1Mask[16];
8634   SDValue V2Mask[16];
8635   V1InUse = false;
8636   V2InUse = false;
8637
8638   int Size = Mask.size();
8639   int Scale = 16 / Size;
8640   for (int i = 0; i < 16; ++i) {
8641     if (Mask[i / Scale] == -1) {
8642       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8643     } else {
8644       const int ZeroMask = 0x80;
8645       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8646                                           : ZeroMask;
8647       int V2Idx = Mask[i / Scale] < Size
8648                       ? ZeroMask
8649                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8650       if (Zeroable[i / Scale])
8651         V1Idx = V2Idx = ZeroMask;
8652       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8653       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8654       V1InUse |= (ZeroMask != V1Idx);
8655       V2InUse |= (ZeroMask != V2Idx);
8656     }
8657   }
8658
8659   if (V1InUse)
8660     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8661                      DAG.getBitcast(MVT::v16i8, V1),
8662                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8663   if (V2InUse)
8664     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8665                      DAG.getBitcast(MVT::v16i8, V2),
8666                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8667
8668   // If we need shuffled inputs from both, blend the two.
8669   SDValue V;
8670   if (V1InUse && V2InUse)
8671     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8672   else
8673     V = V1InUse ? V1 : V2;
8674
8675   // Cast the result back to the correct type.
8676   return DAG.getBitcast(VT, V);
8677 }
8678
8679 /// \brief Generic lowering of 8-lane i16 shuffles.
8680 ///
8681 /// This handles both single-input shuffles and combined shuffle/blends with
8682 /// two inputs. The single input shuffles are immediately delegated to
8683 /// a dedicated lowering routine.
8684 ///
8685 /// The blends are lowered in one of three fundamental ways. If there are few
8686 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8687 /// of the input is significantly cheaper when lowered as an interleaving of
8688 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8689 /// halves of the inputs separately (making them have relatively few inputs)
8690 /// and then concatenate them.
8691 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8692                                        const X86Subtarget *Subtarget,
8693                                        SelectionDAG &DAG) {
8694   SDLoc DL(Op);
8695   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8696   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8697   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8698   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8699   ArrayRef<int> OrigMask = SVOp->getMask();
8700   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8701                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8702   MutableArrayRef<int> Mask(MaskStorage);
8703
8704   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8705
8706   // Whenever we can lower this as a zext, that instruction is strictly faster
8707   // than any alternative.
8708   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8709           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8710     return ZExt;
8711
8712   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8713   (void)isV1;
8714   auto isV2 = [](int M) { return M >= 8; };
8715
8716   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8717
8718   if (NumV2Inputs == 0) {
8719     // Check for being able to broadcast a single element.
8720     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8721                                                           Mask, Subtarget, DAG))
8722       return Broadcast;
8723
8724     // Try to use shift instructions.
8725     if (SDValue Shift =
8726             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8727       return Shift;
8728
8729     // Use dedicated unpack instructions for masks that match their pattern.
8730     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8731       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8732     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8733       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8734
8735     // Try to use byte rotation instructions.
8736     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8737                                                         Mask, Subtarget, DAG))
8738       return Rotate;
8739
8740     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8741                                                      Subtarget, DAG);
8742   }
8743
8744   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8745          "All single-input shuffles should be canonicalized to be V1-input "
8746          "shuffles.");
8747
8748   // Try to use shift instructions.
8749   if (SDValue Shift =
8750           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8751     return Shift;
8752
8753   // See if we can use SSE4A Extraction / Insertion.
8754   if (Subtarget->hasSSE4A())
8755     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8756       return V;
8757
8758   // There are special ways we can lower some single-element blends.
8759   if (NumV2Inputs == 1)
8760     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8761                                                          Mask, Subtarget, DAG))
8762       return V;
8763
8764   // We have different paths for blend lowering, but they all must use the
8765   // *exact* same predicate.
8766   bool IsBlendSupported = Subtarget->hasSSE41();
8767   if (IsBlendSupported)
8768     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8769                                                   Subtarget, DAG))
8770       return Blend;
8771
8772   if (SDValue Masked =
8773           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8774     return Masked;
8775
8776   // Use dedicated unpack instructions for masks that match their pattern.
8777   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8778     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8779   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8780     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8781
8782   // Try to use byte rotation instructions.
8783   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8784           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8785     return Rotate;
8786
8787   if (SDValue BitBlend =
8788           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8789     return BitBlend;
8790
8791   if (SDValue Unpack =
8792           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8793     return Unpack;
8794
8795   // If we can't directly blend but can use PSHUFB, that will be better as it
8796   // can both shuffle and set up the inefficient blend.
8797   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8798     bool V1InUse, V2InUse;
8799     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8800                                       V1InUse, V2InUse);
8801   }
8802
8803   // We can always bit-blend if we have to so the fallback strategy is to
8804   // decompose into single-input permutes and blends.
8805   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8806                                                       Mask, DAG);
8807 }
8808
8809 /// \brief Check whether a compaction lowering can be done by dropping even
8810 /// elements and compute how many times even elements must be dropped.
8811 ///
8812 /// This handles shuffles which take every Nth element where N is a power of
8813 /// two. Example shuffle masks:
8814 ///
8815 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8816 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8817 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8818 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8819 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8820 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8821 ///
8822 /// Any of these lanes can of course be undef.
8823 ///
8824 /// This routine only supports N <= 3.
8825 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8826 /// for larger N.
8827 ///
8828 /// \returns N above, or the number of times even elements must be dropped if
8829 /// there is such a number. Otherwise returns zero.
8830 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8831   // Figure out whether we're looping over two inputs or just one.
8832   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8833
8834   // The modulus for the shuffle vector entries is based on whether this is
8835   // a single input or not.
8836   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8837   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8838          "We should only be called with masks with a power-of-2 size!");
8839
8840   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8841
8842   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8843   // and 2^3 simultaneously. This is because we may have ambiguity with
8844   // partially undef inputs.
8845   bool ViableForN[3] = {true, true, true};
8846
8847   for (int i = 0, e = Mask.size(); i < e; ++i) {
8848     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8849     // want.
8850     if (Mask[i] == -1)
8851       continue;
8852
8853     bool IsAnyViable = false;
8854     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8855       if (ViableForN[j]) {
8856         uint64_t N = j + 1;
8857
8858         // The shuffle mask must be equal to (i * 2^N) % M.
8859         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8860           IsAnyViable = true;
8861         else
8862           ViableForN[j] = false;
8863       }
8864     // Early exit if we exhaust the possible powers of two.
8865     if (!IsAnyViable)
8866       break;
8867   }
8868
8869   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8870     if (ViableForN[j])
8871       return j + 1;
8872
8873   // Return 0 as there is no viable power of two.
8874   return 0;
8875 }
8876
8877 /// \brief Generic lowering of v16i8 shuffles.
8878 ///
8879 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8880 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8881 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8882 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8883 /// back together.
8884 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8885                                        const X86Subtarget *Subtarget,
8886                                        SelectionDAG &DAG) {
8887   SDLoc DL(Op);
8888   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8889   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8890   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8891   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8892   ArrayRef<int> Mask = SVOp->getMask();
8893   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8894
8895   // Try to use shift instructions.
8896   if (SDValue Shift =
8897           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8898     return Shift;
8899
8900   // Try to use byte rotation instructions.
8901   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8902           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8903     return Rotate;
8904
8905   // Try to use a zext lowering.
8906   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8907           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8908     return ZExt;
8909
8910   // See if we can use SSE4A Extraction / Insertion.
8911   if (Subtarget->hasSSE4A())
8912     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8913       return V;
8914
8915   int NumV2Elements =
8916       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8917
8918   // For single-input shuffles, there are some nicer lowering tricks we can use.
8919   if (NumV2Elements == 0) {
8920     // Check for being able to broadcast a single element.
8921     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8922                                                           Mask, Subtarget, DAG))
8923       return Broadcast;
8924
8925     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8926     // Notably, this handles splat and partial-splat shuffles more efficiently.
8927     // However, it only makes sense if the pre-duplication shuffle simplifies
8928     // things significantly. Currently, this means we need to be able to
8929     // express the pre-duplication shuffle as an i16 shuffle.
8930     //
8931     // FIXME: We should check for other patterns which can be widened into an
8932     // i16 shuffle as well.
8933     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8934       for (int i = 0; i < 16; i += 2)
8935         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8936           return false;
8937
8938       return true;
8939     };
8940     auto tryToWidenViaDuplication = [&]() -> SDValue {
8941       if (!canWidenViaDuplication(Mask))
8942         return SDValue();
8943       SmallVector<int, 4> LoInputs;
8944       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8945                    [](int M) { return M >= 0 && M < 8; });
8946       std::sort(LoInputs.begin(), LoInputs.end());
8947       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8948                      LoInputs.end());
8949       SmallVector<int, 4> HiInputs;
8950       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8951                    [](int M) { return M >= 8; });
8952       std::sort(HiInputs.begin(), HiInputs.end());
8953       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8954                      HiInputs.end());
8955
8956       bool TargetLo = LoInputs.size() >= HiInputs.size();
8957       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8958       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8959
8960       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8961       SmallDenseMap<int, int, 8> LaneMap;
8962       for (int I : InPlaceInputs) {
8963         PreDupI16Shuffle[I/2] = I/2;
8964         LaneMap[I] = I;
8965       }
8966       int j = TargetLo ? 0 : 4, je = j + 4;
8967       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8968         // Check if j is already a shuffle of this input. This happens when
8969         // there are two adjacent bytes after we move the low one.
8970         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8971           // If we haven't yet mapped the input, search for a slot into which
8972           // we can map it.
8973           while (j < je && PreDupI16Shuffle[j] != -1)
8974             ++j;
8975
8976           if (j == je)
8977             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8978             return SDValue();
8979
8980           // Map this input with the i16 shuffle.
8981           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8982         }
8983
8984         // Update the lane map based on the mapping we ended up with.
8985         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8986       }
8987       V1 = DAG.getBitcast(
8988           MVT::v16i8,
8989           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
8990                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8991
8992       // Unpack the bytes to form the i16s that will be shuffled into place.
8993       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8994                        MVT::v16i8, V1, V1);
8995
8996       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8997       for (int i = 0; i < 16; ++i)
8998         if (Mask[i] != -1) {
8999           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9000           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9001           if (PostDupI16Shuffle[i / 2] == -1)
9002             PostDupI16Shuffle[i / 2] = MappedMask;
9003           else
9004             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9005                    "Conflicting entrties in the original shuffle!");
9006         }
9007       return DAG.getBitcast(
9008           MVT::v16i8,
9009           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9010                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9011     };
9012     if (SDValue V = tryToWidenViaDuplication())
9013       return V;
9014   }
9015
9016   // Use dedicated unpack instructions for masks that match their pattern.
9017   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9018                                          0, 16, 1, 17, 2, 18, 3, 19,
9019                                          // High half.
9020                                          4, 20, 5, 21, 6, 22, 7, 23}))
9021     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9022   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9023                                          8, 24, 9, 25, 10, 26, 11, 27,
9024                                          // High half.
9025                                          12, 28, 13, 29, 14, 30, 15, 31}))
9026     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9027
9028   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9029   // with PSHUFB. It is important to do this before we attempt to generate any
9030   // blends but after all of the single-input lowerings. If the single input
9031   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9032   // want to preserve that and we can DAG combine any longer sequences into
9033   // a PSHUFB in the end. But once we start blending from multiple inputs,
9034   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9035   // and there are *very* few patterns that would actually be faster than the
9036   // PSHUFB approach because of its ability to zero lanes.
9037   //
9038   // FIXME: The only exceptions to the above are blends which are exact
9039   // interleavings with direct instructions supporting them. We currently don't
9040   // handle those well here.
9041   if (Subtarget->hasSSSE3()) {
9042     bool V1InUse = false;
9043     bool V2InUse = false;
9044
9045     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9046                                                 DAG, V1InUse, V2InUse);
9047
9048     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9049     // do so. This avoids using them to handle blends-with-zero which is
9050     // important as a single pshufb is significantly faster for that.
9051     if (V1InUse && V2InUse) {
9052       if (Subtarget->hasSSE41())
9053         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9054                                                       Mask, Subtarget, DAG))
9055           return Blend;
9056
9057       // We can use an unpack to do the blending rather than an or in some
9058       // cases. Even though the or may be (very minorly) more efficient, we
9059       // preference this lowering because there are common cases where part of
9060       // the complexity of the shuffles goes away when we do the final blend as
9061       // an unpack.
9062       // FIXME: It might be worth trying to detect if the unpack-feeding
9063       // shuffles will both be pshufb, in which case we shouldn't bother with
9064       // this.
9065       if (SDValue Unpack =
9066               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9067         return Unpack;
9068     }
9069
9070     return PSHUFB;
9071   }
9072
9073   // There are special ways we can lower some single-element blends.
9074   if (NumV2Elements == 1)
9075     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9076                                                          Mask, Subtarget, DAG))
9077       return V;
9078
9079   if (SDValue BitBlend =
9080           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9081     return BitBlend;
9082
9083   // Check whether a compaction lowering can be done. This handles shuffles
9084   // which take every Nth element for some even N. See the helper function for
9085   // details.
9086   //
9087   // We special case these as they can be particularly efficiently handled with
9088   // the PACKUSB instruction on x86 and they show up in common patterns of
9089   // rearranging bytes to truncate wide elements.
9090   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9091     // NumEvenDrops is the power of two stride of the elements. Another way of
9092     // thinking about it is that we need to drop the even elements this many
9093     // times to get the original input.
9094     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9095
9096     // First we need to zero all the dropped bytes.
9097     assert(NumEvenDrops <= 3 &&
9098            "No support for dropping even elements more than 3 times.");
9099     // We use the mask type to pick which bytes are preserved based on how many
9100     // elements are dropped.
9101     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9102     SDValue ByteClearMask = DAG.getBitcast(
9103         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9104     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9105     if (!IsSingleInput)
9106       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9107
9108     // Now pack things back together.
9109     V1 = DAG.getBitcast(MVT::v8i16, V1);
9110     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9111     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9112     for (int i = 1; i < NumEvenDrops; ++i) {
9113       Result = DAG.getBitcast(MVT::v8i16, Result);
9114       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9115     }
9116
9117     return Result;
9118   }
9119
9120   // Handle multi-input cases by blending single-input shuffles.
9121   if (NumV2Elements > 0)
9122     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9123                                                       Mask, DAG);
9124
9125   // The fallback path for single-input shuffles widens this into two v8i16
9126   // vectors with unpacks, shuffles those, and then pulls them back together
9127   // with a pack.
9128   SDValue V = V1;
9129
9130   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9131   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9132   for (int i = 0; i < 16; ++i)
9133     if (Mask[i] >= 0)
9134       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9135
9136   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9137
9138   SDValue VLoHalf, VHiHalf;
9139   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9140   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9141   // i16s.
9142   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9143                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9144       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9145                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9146     // Use a mask to drop the high bytes.
9147     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9148     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9149                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9150
9151     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9152     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9153
9154     // Squash the masks to point directly into VLoHalf.
9155     for (int &M : LoBlendMask)
9156       if (M >= 0)
9157         M /= 2;
9158     for (int &M : HiBlendMask)
9159       if (M >= 0)
9160         M /= 2;
9161   } else {
9162     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9163     // VHiHalf so that we can blend them as i16s.
9164     VLoHalf = DAG.getBitcast(
9165         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9166     VHiHalf = DAG.getBitcast(
9167         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9168   }
9169
9170   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9171   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9172
9173   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9174 }
9175
9176 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9177 ///
9178 /// This routine breaks down the specific type of 128-bit shuffle and
9179 /// dispatches to the lowering routines accordingly.
9180 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9181                                         MVT VT, const X86Subtarget *Subtarget,
9182                                         SelectionDAG &DAG) {
9183   switch (VT.SimpleTy) {
9184   case MVT::v2i64:
9185     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9186   case MVT::v2f64:
9187     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9188   case MVT::v4i32:
9189     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9190   case MVT::v4f32:
9191     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9192   case MVT::v8i16:
9193     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9194   case MVT::v16i8:
9195     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9196
9197   default:
9198     llvm_unreachable("Unimplemented!");
9199   }
9200 }
9201
9202 /// \brief Helper function to test whether a shuffle mask could be
9203 /// simplified by widening the elements being shuffled.
9204 ///
9205 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9206 /// leaves it in an unspecified state.
9207 ///
9208 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9209 /// shuffle masks. The latter have the special property of a '-2' representing
9210 /// a zero-ed lane of a vector.
9211 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9212                                     SmallVectorImpl<int> &WidenedMask) {
9213   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9214     // If both elements are undef, its trivial.
9215     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9216       WidenedMask.push_back(SM_SentinelUndef);
9217       continue;
9218     }
9219
9220     // Check for an undef mask and a mask value properly aligned to fit with
9221     // a pair of values. If we find such a case, use the non-undef mask's value.
9222     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9223       WidenedMask.push_back(Mask[i + 1] / 2);
9224       continue;
9225     }
9226     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9227       WidenedMask.push_back(Mask[i] / 2);
9228       continue;
9229     }
9230
9231     // When zeroing, we need to spread the zeroing across both lanes to widen.
9232     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9233       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9234           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9235         WidenedMask.push_back(SM_SentinelZero);
9236         continue;
9237       }
9238       return false;
9239     }
9240
9241     // Finally check if the two mask values are adjacent and aligned with
9242     // a pair.
9243     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9244       WidenedMask.push_back(Mask[i] / 2);
9245       continue;
9246     }
9247
9248     // Otherwise we can't safely widen the elements used in this shuffle.
9249     return false;
9250   }
9251   assert(WidenedMask.size() == Mask.size() / 2 &&
9252          "Incorrect size of mask after widening the elements!");
9253
9254   return true;
9255 }
9256
9257 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9258 ///
9259 /// This routine just extracts two subvectors, shuffles them independently, and
9260 /// then concatenates them back together. This should work effectively with all
9261 /// AVX vector shuffle types.
9262 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9263                                           SDValue V2, ArrayRef<int> Mask,
9264                                           SelectionDAG &DAG) {
9265   assert(VT.getSizeInBits() >= 256 &&
9266          "Only for 256-bit or wider vector shuffles!");
9267   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9268   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9269
9270   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9271   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9272
9273   int NumElements = VT.getVectorNumElements();
9274   int SplitNumElements = NumElements / 2;
9275   MVT ScalarVT = VT.getScalarType();
9276   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9277
9278   // Rather than splitting build-vectors, just build two narrower build
9279   // vectors. This helps shuffling with splats and zeros.
9280   auto SplitVector = [&](SDValue V) {
9281     while (V.getOpcode() == ISD::BITCAST)
9282       V = V->getOperand(0);
9283
9284     MVT OrigVT = V.getSimpleValueType();
9285     int OrigNumElements = OrigVT.getVectorNumElements();
9286     int OrigSplitNumElements = OrigNumElements / 2;
9287     MVT OrigScalarVT = OrigVT.getScalarType();
9288     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9289
9290     SDValue LoV, HiV;
9291
9292     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9293     if (!BV) {
9294       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9295                         DAG.getIntPtrConstant(0, DL));
9296       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9297                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9298     } else {
9299
9300       SmallVector<SDValue, 16> LoOps, HiOps;
9301       for (int i = 0; i < OrigSplitNumElements; ++i) {
9302         LoOps.push_back(BV->getOperand(i));
9303         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9304       }
9305       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9306       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9307     }
9308     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9309                           DAG.getBitcast(SplitVT, HiV));
9310   };
9311
9312   SDValue LoV1, HiV1, LoV2, HiV2;
9313   std::tie(LoV1, HiV1) = SplitVector(V1);
9314   std::tie(LoV2, HiV2) = SplitVector(V2);
9315
9316   // Now create two 4-way blends of these half-width vectors.
9317   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9318     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9319     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9320     for (int i = 0; i < SplitNumElements; ++i) {
9321       int M = HalfMask[i];
9322       if (M >= NumElements) {
9323         if (M >= NumElements + SplitNumElements)
9324           UseHiV2 = true;
9325         else
9326           UseLoV2 = true;
9327         V2BlendMask.push_back(M - NumElements);
9328         V1BlendMask.push_back(-1);
9329         BlendMask.push_back(SplitNumElements + i);
9330       } else if (M >= 0) {
9331         if (M >= SplitNumElements)
9332           UseHiV1 = true;
9333         else
9334           UseLoV1 = true;
9335         V2BlendMask.push_back(-1);
9336         V1BlendMask.push_back(M);
9337         BlendMask.push_back(i);
9338       } else {
9339         V2BlendMask.push_back(-1);
9340         V1BlendMask.push_back(-1);
9341         BlendMask.push_back(-1);
9342       }
9343     }
9344
9345     // Because the lowering happens after all combining takes place, we need to
9346     // manually combine these blend masks as much as possible so that we create
9347     // a minimal number of high-level vector shuffle nodes.
9348
9349     // First try just blending the halves of V1 or V2.
9350     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9351       return DAG.getUNDEF(SplitVT);
9352     if (!UseLoV2 && !UseHiV2)
9353       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9354     if (!UseLoV1 && !UseHiV1)
9355       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9356
9357     SDValue V1Blend, V2Blend;
9358     if (UseLoV1 && UseHiV1) {
9359       V1Blend =
9360         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9361     } else {
9362       // We only use half of V1 so map the usage down into the final blend mask.
9363       V1Blend = UseLoV1 ? LoV1 : HiV1;
9364       for (int i = 0; i < SplitNumElements; ++i)
9365         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9366           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9367     }
9368     if (UseLoV2 && UseHiV2) {
9369       V2Blend =
9370         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9371     } else {
9372       // We only use half of V2 so map the usage down into the final blend mask.
9373       V2Blend = UseLoV2 ? LoV2 : HiV2;
9374       for (int i = 0; i < SplitNumElements; ++i)
9375         if (BlendMask[i] >= SplitNumElements)
9376           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9377     }
9378     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9379   };
9380   SDValue Lo = HalfBlend(LoMask);
9381   SDValue Hi = HalfBlend(HiMask);
9382   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9383 }
9384
9385 /// \brief Either split a vector in halves or decompose the shuffles and the
9386 /// blend.
9387 ///
9388 /// This is provided as a good fallback for many lowerings of non-single-input
9389 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9390 /// between splitting the shuffle into 128-bit components and stitching those
9391 /// back together vs. extracting the single-input shuffles and blending those
9392 /// results.
9393 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9394                                                 SDValue V2, ArrayRef<int> Mask,
9395                                                 SelectionDAG &DAG) {
9396   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9397                                             "lower single-input shuffles as it "
9398                                             "could then recurse on itself.");
9399   int Size = Mask.size();
9400
9401   // If this can be modeled as a broadcast of two elements followed by a blend,
9402   // prefer that lowering. This is especially important because broadcasts can
9403   // often fold with memory operands.
9404   auto DoBothBroadcast = [&] {
9405     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9406     for (int M : Mask)
9407       if (M >= Size) {
9408         if (V2BroadcastIdx == -1)
9409           V2BroadcastIdx = M - Size;
9410         else if (M - Size != V2BroadcastIdx)
9411           return false;
9412       } else if (M >= 0) {
9413         if (V1BroadcastIdx == -1)
9414           V1BroadcastIdx = M;
9415         else if (M != V1BroadcastIdx)
9416           return false;
9417       }
9418     return true;
9419   };
9420   if (DoBothBroadcast())
9421     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9422                                                       DAG);
9423
9424   // If the inputs all stem from a single 128-bit lane of each input, then we
9425   // split them rather than blending because the split will decompose to
9426   // unusually few instructions.
9427   int LaneCount = VT.getSizeInBits() / 128;
9428   int LaneSize = Size / LaneCount;
9429   SmallBitVector LaneInputs[2];
9430   LaneInputs[0].resize(LaneCount, false);
9431   LaneInputs[1].resize(LaneCount, false);
9432   for (int i = 0; i < Size; ++i)
9433     if (Mask[i] >= 0)
9434       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9435   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9436     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9437
9438   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9439   // that the decomposed single-input shuffles don't end up here.
9440   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9441 }
9442
9443 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9444 /// a permutation and blend of those lanes.
9445 ///
9446 /// This essentially blends the out-of-lane inputs to each lane into the lane
9447 /// from a permuted copy of the vector. This lowering strategy results in four
9448 /// instructions in the worst case for a single-input cross lane shuffle which
9449 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9450 /// of. Special cases for each particular shuffle pattern should be handled
9451 /// prior to trying this lowering.
9452 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9453                                                        SDValue V1, SDValue V2,
9454                                                        ArrayRef<int> Mask,
9455                                                        SelectionDAG &DAG) {
9456   // FIXME: This should probably be generalized for 512-bit vectors as well.
9457   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9458   int LaneSize = Mask.size() / 2;
9459
9460   // If there are only inputs from one 128-bit lane, splitting will in fact be
9461   // less expensive. The flags track whether the given lane contains an element
9462   // that crosses to another lane.
9463   bool LaneCrossing[2] = {false, false};
9464   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9465     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9466       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9467   if (!LaneCrossing[0] || !LaneCrossing[1])
9468     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9469
9470   if (isSingleInputShuffleMask(Mask)) {
9471     SmallVector<int, 32> FlippedBlendMask;
9472     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9473       FlippedBlendMask.push_back(
9474           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9475                                   ? Mask[i]
9476                                   : Mask[i] % LaneSize +
9477                                         (i / LaneSize) * LaneSize + Size));
9478
9479     // Flip the vector, and blend the results which should now be in-lane. The
9480     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9481     // 5 for the high source. The value 3 selects the high half of source 2 and
9482     // the value 2 selects the low half of source 2. We only use source 2 to
9483     // allow folding it into a memory operand.
9484     unsigned PERMMask = 3 | 2 << 4;
9485     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9486                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9487     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9488   }
9489
9490   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9491   // will be handled by the above logic and a blend of the results, much like
9492   // other patterns in AVX.
9493   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9494 }
9495
9496 /// \brief Handle lowering 2-lane 128-bit shuffles.
9497 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9498                                         SDValue V2, ArrayRef<int> Mask,
9499                                         const X86Subtarget *Subtarget,
9500                                         SelectionDAG &DAG) {
9501   // TODO: If minimizing size and one of the inputs is a zero vector and the
9502   // the zero vector has only one use, we could use a VPERM2X128 to save the
9503   // instruction bytes needed to explicitly generate the zero vector.
9504
9505   // Blends are faster and handle all the non-lane-crossing cases.
9506   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9507                                                 Subtarget, DAG))
9508     return Blend;
9509
9510   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9511   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9512
9513   // If either input operand is a zero vector, use VPERM2X128 because its mask
9514   // allows us to replace the zero input with an implicit zero.
9515   if (!IsV1Zero && !IsV2Zero) {
9516     // Check for patterns which can be matched with a single insert of a 128-bit
9517     // subvector.
9518     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9519     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9520       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9521                                    VT.getVectorNumElements() / 2);
9522       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9523                                 DAG.getIntPtrConstant(0, DL));
9524       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9525                                 OnlyUsesV1 ? V1 : V2,
9526                                 DAG.getIntPtrConstant(0, DL));
9527       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9528     }
9529   }
9530
9531   // Otherwise form a 128-bit permutation. After accounting for undefs,
9532   // convert the 64-bit shuffle mask selection values into 128-bit
9533   // selection bits by dividing the indexes by 2 and shifting into positions
9534   // defined by a vperm2*128 instruction's immediate control byte.
9535
9536   // The immediate permute control byte looks like this:
9537   //    [1:0] - select 128 bits from sources for low half of destination
9538   //    [2]   - ignore
9539   //    [3]   - zero low half of destination
9540   //    [5:4] - select 128 bits from sources for high half of destination
9541   //    [6]   - ignore
9542   //    [7]   - zero high half of destination
9543
9544   int MaskLO = Mask[0];
9545   if (MaskLO == SM_SentinelUndef)
9546     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9547
9548   int MaskHI = Mask[2];
9549   if (MaskHI == SM_SentinelUndef)
9550     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9551
9552   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9553
9554   // If either input is a zero vector, replace it with an undef input.
9555   // Shuffle mask values <  4 are selecting elements of V1.
9556   // Shuffle mask values >= 4 are selecting elements of V2.
9557   // Adjust each half of the permute mask by clearing the half that was
9558   // selecting the zero vector and setting the zero mask bit.
9559   if (IsV1Zero) {
9560     V1 = DAG.getUNDEF(VT);
9561     if (MaskLO < 4)
9562       PermMask = (PermMask & 0xf0) | 0x08;
9563     if (MaskHI < 4)
9564       PermMask = (PermMask & 0x0f) | 0x80;
9565   }
9566   if (IsV2Zero) {
9567     V2 = DAG.getUNDEF(VT);
9568     if (MaskLO >= 4)
9569       PermMask = (PermMask & 0xf0) | 0x08;
9570     if (MaskHI >= 4)
9571       PermMask = (PermMask & 0x0f) | 0x80;
9572   }
9573
9574   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9575                      DAG.getConstant(PermMask, DL, MVT::i8));
9576 }
9577
9578 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9579 /// shuffling each lane.
9580 ///
9581 /// This will only succeed when the result of fixing the 128-bit lanes results
9582 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9583 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9584 /// the lane crosses early and then use simpler shuffles within each lane.
9585 ///
9586 /// FIXME: It might be worthwhile at some point to support this without
9587 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9588 /// in x86 only floating point has interesting non-repeating shuffles, and even
9589 /// those are still *marginally* more expensive.
9590 static SDValue lowerVectorShuffleByMerging128BitLanes(
9591     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9592     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9593   assert(!isSingleInputShuffleMask(Mask) &&
9594          "This is only useful with multiple inputs.");
9595
9596   int Size = Mask.size();
9597   int LaneSize = 128 / VT.getScalarSizeInBits();
9598   int NumLanes = Size / LaneSize;
9599   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9600
9601   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9602   // check whether the in-128-bit lane shuffles share a repeating pattern.
9603   SmallVector<int, 4> Lanes;
9604   Lanes.resize(NumLanes, -1);
9605   SmallVector<int, 4> InLaneMask;
9606   InLaneMask.resize(LaneSize, -1);
9607   for (int i = 0; i < Size; ++i) {
9608     if (Mask[i] < 0)
9609       continue;
9610
9611     int j = i / LaneSize;
9612
9613     if (Lanes[j] < 0) {
9614       // First entry we've seen for this lane.
9615       Lanes[j] = Mask[i] / LaneSize;
9616     } else if (Lanes[j] != Mask[i] / LaneSize) {
9617       // This doesn't match the lane selected previously!
9618       return SDValue();
9619     }
9620
9621     // Check that within each lane we have a consistent shuffle mask.
9622     int k = i % LaneSize;
9623     if (InLaneMask[k] < 0) {
9624       InLaneMask[k] = Mask[i] % LaneSize;
9625     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9626       // This doesn't fit a repeating in-lane mask.
9627       return SDValue();
9628     }
9629   }
9630
9631   // First shuffle the lanes into place.
9632   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9633                                 VT.getSizeInBits() / 64);
9634   SmallVector<int, 8> LaneMask;
9635   LaneMask.resize(NumLanes * 2, -1);
9636   for (int i = 0; i < NumLanes; ++i)
9637     if (Lanes[i] >= 0) {
9638       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9639       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9640     }
9641
9642   V1 = DAG.getBitcast(LaneVT, V1);
9643   V2 = DAG.getBitcast(LaneVT, V2);
9644   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9645
9646   // Cast it back to the type we actually want.
9647   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9648
9649   // Now do a simple shuffle that isn't lane crossing.
9650   SmallVector<int, 8> NewMask;
9651   NewMask.resize(Size, -1);
9652   for (int i = 0; i < Size; ++i)
9653     if (Mask[i] >= 0)
9654       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9655   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9656          "Must not introduce lane crosses at this point!");
9657
9658   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9659 }
9660
9661 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9662 /// given mask.
9663 ///
9664 /// This returns true if the elements from a particular input are already in the
9665 /// slot required by the given mask and require no permutation.
9666 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9667   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9668   int Size = Mask.size();
9669   for (int i = 0; i < Size; ++i)
9670     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9671       return false;
9672
9673   return true;
9674 }
9675
9676 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9677                                             ArrayRef<int> Mask, SDValue V1,
9678                                             SDValue V2, SelectionDAG &DAG) {
9679
9680   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9681   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9682   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9683   int NumElts = VT.getVectorNumElements();
9684   bool ShufpdMask = true;
9685   bool CommutableMask = true;
9686   unsigned Immediate = 0;
9687   for (int i = 0; i < NumElts; ++i) {
9688     if (Mask[i] < 0)
9689       continue;
9690     int Val = (i & 6) + NumElts * (i & 1);
9691     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9692     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9693       ShufpdMask = false;
9694     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9695       CommutableMask = false;
9696     Immediate |= (Mask[i] % 2) << i;
9697   }
9698   if (ShufpdMask)
9699     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9700                        DAG.getConstant(Immediate, DL, MVT::i8));
9701   if (CommutableMask)
9702     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9703                        DAG.getConstant(Immediate, DL, MVT::i8));
9704   return SDValue();
9705 }
9706
9707 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9708 ///
9709 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9710 /// isn't available.
9711 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9712                                        const X86Subtarget *Subtarget,
9713                                        SelectionDAG &DAG) {
9714   SDLoc DL(Op);
9715   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9716   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9717   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9718   ArrayRef<int> Mask = SVOp->getMask();
9719   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9720
9721   SmallVector<int, 4> WidenedMask;
9722   if (canWidenShuffleElements(Mask, WidenedMask))
9723     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9724                                     DAG);
9725
9726   if (isSingleInputShuffleMask(Mask)) {
9727     // Check for being able to broadcast a single element.
9728     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9729                                                           Mask, Subtarget, DAG))
9730       return Broadcast;
9731
9732     // Use low duplicate instructions for masks that match their pattern.
9733     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9734       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9735
9736     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9737       // Non-half-crossing single input shuffles can be lowerid with an
9738       // interleaved permutation.
9739       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9740                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9741       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9742                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9743     }
9744
9745     // With AVX2 we have direct support for this permutation.
9746     if (Subtarget->hasAVX2())
9747       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9748                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9749
9750     // Otherwise, fall back.
9751     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9752                                                    DAG);
9753   }
9754
9755   // X86 has dedicated unpack instructions that can handle specific blend
9756   // operations: UNPCKH and UNPCKL.
9757   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9758     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9759   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9760     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9761   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9762     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9763   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9764     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9765
9766   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9767                                                 Subtarget, DAG))
9768     return Blend;
9769
9770   // Check if the blend happens to exactly fit that of SHUFPD.
9771   if (SDValue Op =
9772       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9773     return Op;
9774
9775   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9776   // shuffle. However, if we have AVX2 and either inputs are already in place,
9777   // we will be able to shuffle even across lanes the other input in a single
9778   // instruction so skip this pattern.
9779   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9780                                  isShuffleMaskInputInPlace(1, Mask))))
9781     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9782             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9783       return Result;
9784
9785   // If we have AVX2 then we always want to lower with a blend because an v4 we
9786   // can fully permute the elements.
9787   if (Subtarget->hasAVX2())
9788     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9789                                                       Mask, DAG);
9790
9791   // Otherwise fall back on generic lowering.
9792   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9793 }
9794
9795 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9796 ///
9797 /// This routine is only called when we have AVX2 and thus a reasonable
9798 /// instruction set for v4i64 shuffling..
9799 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9800                                        const X86Subtarget *Subtarget,
9801                                        SelectionDAG &DAG) {
9802   SDLoc DL(Op);
9803   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9804   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9805   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9806   ArrayRef<int> Mask = SVOp->getMask();
9807   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9808   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9809
9810   SmallVector<int, 4> WidenedMask;
9811   if (canWidenShuffleElements(Mask, WidenedMask))
9812     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9813                                     DAG);
9814
9815   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, 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::v4i64, V1,
9821                                                         Mask, Subtarget, DAG))
9822     return Broadcast;
9823
9824   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9825   // use lower latency instructions that will operate on both 128-bit lanes.
9826   SmallVector<int, 2> RepeatedMask;
9827   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9828     if (isSingleInputShuffleMask(Mask)) {
9829       int PSHUFDMask[] = {-1, -1, -1, -1};
9830       for (int i = 0; i < 2; ++i)
9831         if (RepeatedMask[i] >= 0) {
9832           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9833           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9834         }
9835       return DAG.getBitcast(
9836           MVT::v4i64,
9837           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9838                       DAG.getBitcast(MVT::v8i32, V1),
9839                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9840     }
9841   }
9842
9843   // AVX2 provides a direct instruction for permuting a single input across
9844   // lanes.
9845   if (isSingleInputShuffleMask(Mask))
9846     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9847                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9848
9849   // Try to use shift instructions.
9850   if (SDValue Shift =
9851           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9852     return Shift;
9853
9854   // Use dedicated unpack instructions for masks that match their pattern.
9855   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9856     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9857   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9858     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9859   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9860     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9861   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9862     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9863
9864   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9865   // shuffle. However, if we have AVX2 and either inputs are already in place,
9866   // we will be able to shuffle even across lanes the other input in a single
9867   // instruction so skip this pattern.
9868   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9869                                  isShuffleMaskInputInPlace(1, Mask))))
9870     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9871             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9872       return Result;
9873
9874   // Otherwise fall back on generic blend lowering.
9875   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9876                                                     Mask, DAG);
9877 }
9878
9879 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9880 ///
9881 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9882 /// isn't available.
9883 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9884                                        const X86Subtarget *Subtarget,
9885                                        SelectionDAG &DAG) {
9886   SDLoc DL(Op);
9887   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9888   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9889   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9890   ArrayRef<int> Mask = SVOp->getMask();
9891   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9892
9893   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9894                                                 Subtarget, DAG))
9895     return Blend;
9896
9897   // Check for being able to broadcast a single element.
9898   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9899                                                         Mask, Subtarget, DAG))
9900     return Broadcast;
9901
9902   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9903   // options to efficiently lower the shuffle.
9904   SmallVector<int, 4> RepeatedMask;
9905   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9906     assert(RepeatedMask.size() == 4 &&
9907            "Repeated masks must be half the mask width!");
9908
9909     // Use even/odd duplicate instructions for masks that match their pattern.
9910     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9911       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9912     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9913       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9914
9915     if (isSingleInputShuffleMask(Mask))
9916       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9917                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9918
9919     // Use dedicated unpack instructions for masks that match their pattern.
9920     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9921       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9922     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9923       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9924     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9925       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9926     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9927       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9928
9929     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9930     // have already handled any direct blends. We also need to squash the
9931     // repeated mask into a simulated v4f32 mask.
9932     for (int i = 0; i < 4; ++i)
9933       if (RepeatedMask[i] >= 8)
9934         RepeatedMask[i] -= 4;
9935     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9936   }
9937
9938   // If we have a single input shuffle with different shuffle patterns in the
9939   // two 128-bit lanes use the variable mask to VPERMILPS.
9940   if (isSingleInputShuffleMask(Mask)) {
9941     SDValue VPermMask[8];
9942     for (int i = 0; i < 8; ++i)
9943       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9944                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9945     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9946       return DAG.getNode(
9947           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9948           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9949
9950     if (Subtarget->hasAVX2())
9951       return DAG.getNode(
9952           X86ISD::VPERMV, DL, MVT::v8f32,
9953           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
9954                                                  MVT::v8i32, VPermMask)),
9955           V1);
9956
9957     // Otherwise, fall back.
9958     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9959                                                    DAG);
9960   }
9961
9962   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9963   // shuffle.
9964   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9965           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9966     return Result;
9967
9968   // If we have AVX2 then we always want to lower with a blend because at v8 we
9969   // can fully permute the elements.
9970   if (Subtarget->hasAVX2())
9971     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9972                                                       Mask, DAG);
9973
9974   // Otherwise fall back on generic lowering.
9975   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9976 }
9977
9978 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9979 ///
9980 /// This routine is only called when we have AVX2 and thus a reasonable
9981 /// instruction set for v8i32 shuffling..
9982 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9983                                        const X86Subtarget *Subtarget,
9984                                        SelectionDAG &DAG) {
9985   SDLoc DL(Op);
9986   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9987   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9988   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9989   ArrayRef<int> Mask = SVOp->getMask();
9990   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9991   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9992
9993   // Whenever we can lower this as a zext, that instruction is strictly faster
9994   // than any alternative. It also allows us to fold memory operands into the
9995   // shuffle in many cases.
9996   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9997                                                          Mask, Subtarget, DAG))
9998     return ZExt;
9999
10000   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10001                                                 Subtarget, DAG))
10002     return Blend;
10003
10004   // Check for being able to broadcast a single element.
10005   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10006                                                         Mask, Subtarget, DAG))
10007     return Broadcast;
10008
10009   // If the shuffle mask is repeated in each 128-bit lane we can use more
10010   // efficient instructions that mirror the shuffles across the two 128-bit
10011   // lanes.
10012   SmallVector<int, 4> RepeatedMask;
10013   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10014     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10015     if (isSingleInputShuffleMask(Mask))
10016       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10017                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10018
10019     // Use dedicated unpack instructions for masks that match their pattern.
10020     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10021       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10022     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10023       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10024     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10025       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10026     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10027       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10028   }
10029
10030   // Try to use shift instructions.
10031   if (SDValue Shift =
10032           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10033     return Shift;
10034
10035   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10036           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10037     return Rotate;
10038
10039   // If the shuffle patterns aren't repeated but it is a single input, directly
10040   // generate a cross-lane VPERMD instruction.
10041   if (isSingleInputShuffleMask(Mask)) {
10042     SDValue VPermMask[8];
10043     for (int i = 0; i < 8; ++i)
10044       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10045                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10046     return DAG.getNode(
10047         X86ISD::VPERMV, DL, MVT::v8i32,
10048         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10049   }
10050
10051   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10052   // shuffle.
10053   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10054           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10055     return Result;
10056
10057   // Otherwise fall back on generic blend lowering.
10058   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10059                                                     Mask, DAG);
10060 }
10061
10062 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10063 ///
10064 /// This routine is only called when we have AVX2 and thus a reasonable
10065 /// instruction set for v16i16 shuffling..
10066 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10067                                         const X86Subtarget *Subtarget,
10068                                         SelectionDAG &DAG) {
10069   SDLoc DL(Op);
10070   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10071   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10072   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10073   ArrayRef<int> Mask = SVOp->getMask();
10074   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10075   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10076
10077   // Whenever we can lower this as a zext, that instruction is strictly faster
10078   // than any alternative. It also allows us to fold memory operands into the
10079   // shuffle in many cases.
10080   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10081                                                          Mask, Subtarget, DAG))
10082     return ZExt;
10083
10084   // Check for being able to broadcast a single element.
10085   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10086                                                         Mask, Subtarget, DAG))
10087     return Broadcast;
10088
10089   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10090                                                 Subtarget, DAG))
10091     return Blend;
10092
10093   // Use dedicated unpack instructions for masks that match their pattern.
10094   if (isShuffleEquivalent(V1, V2, Mask,
10095                           {// First 128-bit lane:
10096                            0, 16, 1, 17, 2, 18, 3, 19,
10097                            // Second 128-bit lane:
10098                            8, 24, 9, 25, 10, 26, 11, 27}))
10099     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10100   if (isShuffleEquivalent(V1, V2, Mask,
10101                           {// First 128-bit lane:
10102                            4, 20, 5, 21, 6, 22, 7, 23,
10103                            // Second 128-bit lane:
10104                            12, 28, 13, 29, 14, 30, 15, 31}))
10105     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10106
10107   // Try to use shift instructions.
10108   if (SDValue Shift =
10109           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10110     return Shift;
10111
10112   // Try to use byte rotation instructions.
10113   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10114           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10115     return Rotate;
10116
10117   if (isSingleInputShuffleMask(Mask)) {
10118     // There are no generalized cross-lane shuffle operations available on i16
10119     // element types.
10120     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10121       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10122                                                      Mask, DAG);
10123
10124     SmallVector<int, 8> RepeatedMask;
10125     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10126       // As this is a single-input shuffle, the repeated mask should be
10127       // a strictly valid v8i16 mask that we can pass through to the v8i16
10128       // lowering to handle even the v16 case.
10129       return lowerV8I16GeneralSingleInputVectorShuffle(
10130           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10131     }
10132
10133     SDValue PSHUFBMask[32];
10134     for (int i = 0; i < 16; ++i) {
10135       if (Mask[i] == -1) {
10136         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10137         continue;
10138       }
10139
10140       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10141       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10142       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10143       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10144     }
10145     return DAG.getBitcast(MVT::v16i16,
10146                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10147                                       DAG.getBitcast(MVT::v32i8, V1),
10148                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10149                                                   MVT::v32i8, PSHUFBMask)));
10150   }
10151
10152   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10153   // shuffle.
10154   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10155           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10156     return Result;
10157
10158   // Otherwise fall back on generic lowering.
10159   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10160 }
10161
10162 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10163 ///
10164 /// This routine is only called when we have AVX2 and thus a reasonable
10165 /// instruction set for v32i8 shuffling..
10166 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10167                                        const X86Subtarget *Subtarget,
10168                                        SelectionDAG &DAG) {
10169   SDLoc DL(Op);
10170   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10171   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10172   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10173   ArrayRef<int> Mask = SVOp->getMask();
10174   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10175   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10176
10177   // Whenever we can lower this as a zext, that instruction is strictly faster
10178   // than any alternative. It also allows us to fold memory operands into the
10179   // shuffle in many cases.
10180   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10181                                                          Mask, Subtarget, DAG))
10182     return ZExt;
10183
10184   // Check for being able to broadcast a single element.
10185   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10186                                                         Mask, Subtarget, DAG))
10187     return Broadcast;
10188
10189   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10190                                                 Subtarget, DAG))
10191     return Blend;
10192
10193   // Use dedicated unpack instructions for masks that match their pattern.
10194   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10195   // 256-bit lanes.
10196   if (isShuffleEquivalent(
10197           V1, V2, Mask,
10198           {// First 128-bit lane:
10199            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10200            // Second 128-bit lane:
10201            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10202     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10203   if (isShuffleEquivalent(
10204           V1, V2, Mask,
10205           {// First 128-bit lane:
10206            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10207            // Second 128-bit lane:
10208            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10209     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10210
10211   // Try to use shift instructions.
10212   if (SDValue Shift =
10213           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10214     return Shift;
10215
10216   // Try to use byte rotation instructions.
10217   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10218           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10219     return Rotate;
10220
10221   if (isSingleInputShuffleMask(Mask)) {
10222     // There are no generalized cross-lane shuffle operations available on i8
10223     // element types.
10224     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10225       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10226                                                      Mask, DAG);
10227
10228     SDValue PSHUFBMask[32];
10229     for (int i = 0; i < 32; ++i)
10230       PSHUFBMask[i] =
10231           Mask[i] < 0
10232               ? DAG.getUNDEF(MVT::i8)
10233               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10234                                 MVT::i8);
10235
10236     return DAG.getNode(
10237         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10238         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10239   }
10240
10241   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10242   // shuffle.
10243   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10244           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10245     return Result;
10246
10247   // Otherwise fall back on generic lowering.
10248   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10249 }
10250
10251 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10252 ///
10253 /// This routine either breaks down the specific type of a 256-bit x86 vector
10254 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10255 /// together based on the available instructions.
10256 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10257                                         MVT VT, const X86Subtarget *Subtarget,
10258                                         SelectionDAG &DAG) {
10259   SDLoc DL(Op);
10260   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10261   ArrayRef<int> Mask = SVOp->getMask();
10262
10263   // If we have a single input to the zero element, insert that into V1 if we
10264   // can do so cheaply.
10265   int NumElts = VT.getVectorNumElements();
10266   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10267     return M >= NumElts;
10268   });
10269
10270   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10271     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10272                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10273       return Insertion;
10274
10275   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10276   // check for those subtargets here and avoid much of the subtarget querying in
10277   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10278   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10279   // floating point types there eventually, just immediately cast everything to
10280   // a float and operate entirely in that domain.
10281   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10282     int ElementBits = VT.getScalarSizeInBits();
10283     if (ElementBits < 32)
10284       // No floating point type available, decompose into 128-bit vectors.
10285       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10286
10287     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10288                                 VT.getVectorNumElements());
10289     V1 = DAG.getBitcast(FpVT, V1);
10290     V2 = DAG.getBitcast(FpVT, V2);
10291     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10292   }
10293
10294   switch (VT.SimpleTy) {
10295   case MVT::v4f64:
10296     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10297   case MVT::v4i64:
10298     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10299   case MVT::v8f32:
10300     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10301   case MVT::v8i32:
10302     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10303   case MVT::v16i16:
10304     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10305   case MVT::v32i8:
10306     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10307
10308   default:
10309     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10310   }
10311 }
10312
10313 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10314 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10315                                        const X86Subtarget *Subtarget,
10316                                        SelectionDAG &DAG) {
10317   SDLoc DL(Op);
10318   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10319   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10320   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10321   ArrayRef<int> Mask = SVOp->getMask();
10322   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10323
10324   // X86 has dedicated unpack instructions that can handle specific blend
10325   // operations: UNPCKH and UNPCKL.
10326   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10327     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10328   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10329     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10330
10331   // FIXME: Implement direct support for this type!
10332   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10333 }
10334
10335 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10336 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10337                                        const X86Subtarget *Subtarget,
10338                                        SelectionDAG &DAG) {
10339   SDLoc DL(Op);
10340   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10341   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10342   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10343   ArrayRef<int> Mask = SVOp->getMask();
10344   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10345
10346   // Use dedicated unpack instructions for masks that match their pattern.
10347   if (isShuffleEquivalent(V1, V2, Mask,
10348                           {// First 128-bit lane.
10349                            0, 16, 1, 17, 4, 20, 5, 21,
10350                            // Second 128-bit lane.
10351                            8, 24, 9, 25, 12, 28, 13, 29}))
10352     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10353   if (isShuffleEquivalent(V1, V2, Mask,
10354                           {// First 128-bit lane.
10355                            2, 18, 3, 19, 6, 22, 7, 23,
10356                            // Second 128-bit lane.
10357                            10, 26, 11, 27, 14, 30, 15, 31}))
10358     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10359
10360   // FIXME: Implement direct support for this type!
10361   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10362 }
10363
10364 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10365 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10366                                        const X86Subtarget *Subtarget,
10367                                        SelectionDAG &DAG) {
10368   SDLoc DL(Op);
10369   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10370   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10371   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10372   ArrayRef<int> Mask = SVOp->getMask();
10373   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10374
10375   // X86 has dedicated unpack instructions that can handle specific blend
10376   // operations: UNPCKH and UNPCKL.
10377   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10378     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10379   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10380     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10381
10382   // FIXME: Implement direct support for this type!
10383   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10384 }
10385
10386 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10387 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10388                                        const X86Subtarget *Subtarget,
10389                                        SelectionDAG &DAG) {
10390   SDLoc DL(Op);
10391   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10392   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10393   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10394   ArrayRef<int> Mask = SVOp->getMask();
10395   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10396
10397   // Use dedicated unpack instructions for masks that match their pattern.
10398   if (isShuffleEquivalent(V1, V2, Mask,
10399                           {// First 128-bit lane.
10400                            0, 16, 1, 17, 4, 20, 5, 21,
10401                            // Second 128-bit lane.
10402                            8, 24, 9, 25, 12, 28, 13, 29}))
10403     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10404   if (isShuffleEquivalent(V1, V2, Mask,
10405                           {// First 128-bit lane.
10406                            2, 18, 3, 19, 6, 22, 7, 23,
10407                            // Second 128-bit lane.
10408                            10, 26, 11, 27, 14, 30, 15, 31}))
10409     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10410
10411   // FIXME: Implement direct support for this type!
10412   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10413 }
10414
10415 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10416 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10417                                         const X86Subtarget *Subtarget,
10418                                         SelectionDAG &DAG) {
10419   SDLoc DL(Op);
10420   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10421   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10422   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10423   ArrayRef<int> Mask = SVOp->getMask();
10424   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10425   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10426
10427   // FIXME: Implement direct support for this type!
10428   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10429 }
10430
10431 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10432 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10433                                        const X86Subtarget *Subtarget,
10434                                        SelectionDAG &DAG) {
10435   SDLoc DL(Op);
10436   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10437   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10438   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10439   ArrayRef<int> Mask = SVOp->getMask();
10440   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10441   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10442
10443   // FIXME: Implement direct support for this type!
10444   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10445 }
10446
10447 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10448 ///
10449 /// This routine either breaks down the specific type of a 512-bit x86 vector
10450 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10451 /// together based on the available instructions.
10452 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10453                                         MVT VT, const X86Subtarget *Subtarget,
10454                                         SelectionDAG &DAG) {
10455   SDLoc DL(Op);
10456   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10457   ArrayRef<int> Mask = SVOp->getMask();
10458   assert(Subtarget->hasAVX512() &&
10459          "Cannot lower 512-bit vectors w/ basic ISA!");
10460
10461   // Check for being able to broadcast a single element.
10462   if (SDValue Broadcast =
10463           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10464     return Broadcast;
10465
10466   // Dispatch to each element type for lowering. If we don't have supprot for
10467   // specific element type shuffles at 512 bits, immediately split them and
10468   // lower them. Each lowering routine of a given type is allowed to assume that
10469   // the requisite ISA extensions for that element type are available.
10470   switch (VT.SimpleTy) {
10471   case MVT::v8f64:
10472     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10473   case MVT::v16f32:
10474     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10475   case MVT::v8i64:
10476     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10477   case MVT::v16i32:
10478     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10479   case MVT::v32i16:
10480     if (Subtarget->hasBWI())
10481       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10482     break;
10483   case MVT::v64i8:
10484     if (Subtarget->hasBWI())
10485       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10486     break;
10487
10488   default:
10489     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10490   }
10491
10492   // Otherwise fall back on splitting.
10493   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10494 }
10495
10496 /// \brief Top-level lowering for x86 vector shuffles.
10497 ///
10498 /// This handles decomposition, canonicalization, and lowering of all x86
10499 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10500 /// above in helper routines. The canonicalization attempts to widen shuffles
10501 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10502 /// s.t. only one of the two inputs needs to be tested, etc.
10503 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10504                                   SelectionDAG &DAG) {
10505   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10506   ArrayRef<int> Mask = SVOp->getMask();
10507   SDValue V1 = Op.getOperand(0);
10508   SDValue V2 = Op.getOperand(1);
10509   MVT VT = Op.getSimpleValueType();
10510   int NumElements = VT.getVectorNumElements();
10511   SDLoc dl(Op);
10512
10513   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10514
10515   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10516   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10517   if (V1IsUndef && V2IsUndef)
10518     return DAG.getUNDEF(VT);
10519
10520   // When we create a shuffle node we put the UNDEF node to second operand,
10521   // but in some cases the first operand may be transformed to UNDEF.
10522   // In this case we should just commute the node.
10523   if (V1IsUndef)
10524     return DAG.getCommutedVectorShuffle(*SVOp);
10525
10526   // Check for non-undef masks pointing at an undef vector and make the masks
10527   // undef as well. This makes it easier to match the shuffle based solely on
10528   // the mask.
10529   if (V2IsUndef)
10530     for (int M : Mask)
10531       if (M >= NumElements) {
10532         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10533         for (int &M : NewMask)
10534           if (M >= NumElements)
10535             M = -1;
10536         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10537       }
10538
10539   // We actually see shuffles that are entirely re-arrangements of a set of
10540   // zero inputs. This mostly happens while decomposing complex shuffles into
10541   // simple ones. Directly lower these as a buildvector of zeros.
10542   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10543   if (Zeroable.all())
10544     return getZeroVector(VT, Subtarget, DAG, dl);
10545
10546   // Try to collapse shuffles into using a vector type with fewer elements but
10547   // wider element types. We cap this to not form integers or floating point
10548   // elements wider than 64 bits, but it might be interesting to form i128
10549   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10550   SmallVector<int, 16> WidenedMask;
10551   if (VT.getScalarSizeInBits() < 64 &&
10552       canWidenShuffleElements(Mask, WidenedMask)) {
10553     MVT NewEltVT = VT.isFloatingPoint()
10554                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10555                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10556     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10557     // Make sure that the new vector type is legal. For example, v2f64 isn't
10558     // legal on SSE1.
10559     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10560       V1 = DAG.getBitcast(NewVT, V1);
10561       V2 = DAG.getBitcast(NewVT, V2);
10562       return DAG.getBitcast(
10563           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10564     }
10565   }
10566
10567   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10568   for (int M : SVOp->getMask())
10569     if (M < 0)
10570       ++NumUndefElements;
10571     else if (M < NumElements)
10572       ++NumV1Elements;
10573     else
10574       ++NumV2Elements;
10575
10576   // Commute the shuffle as needed such that more elements come from V1 than
10577   // V2. This allows us to match the shuffle pattern strictly on how many
10578   // elements come from V1 without handling the symmetric cases.
10579   if (NumV2Elements > NumV1Elements)
10580     return DAG.getCommutedVectorShuffle(*SVOp);
10581
10582   // When the number of V1 and V2 elements are the same, try to minimize the
10583   // number of uses of V2 in the low half of the vector. When that is tied,
10584   // ensure that the sum of indices for V1 is equal to or lower than the sum
10585   // indices for V2. When those are equal, try to ensure that the number of odd
10586   // indices for V1 is lower than the number of odd indices for V2.
10587   if (NumV1Elements == NumV2Elements) {
10588     int LowV1Elements = 0, LowV2Elements = 0;
10589     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10590       if (M >= NumElements)
10591         ++LowV2Elements;
10592       else if (M >= 0)
10593         ++LowV1Elements;
10594     if (LowV2Elements > LowV1Elements) {
10595       return DAG.getCommutedVectorShuffle(*SVOp);
10596     } else if (LowV2Elements == LowV1Elements) {
10597       int SumV1Indices = 0, SumV2Indices = 0;
10598       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10599         if (SVOp->getMask()[i] >= NumElements)
10600           SumV2Indices += i;
10601         else if (SVOp->getMask()[i] >= 0)
10602           SumV1Indices += i;
10603       if (SumV2Indices < SumV1Indices) {
10604         return DAG.getCommutedVectorShuffle(*SVOp);
10605       } else if (SumV2Indices == SumV1Indices) {
10606         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10607         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10608           if (SVOp->getMask()[i] >= NumElements)
10609             NumV2OddIndices += i % 2;
10610           else if (SVOp->getMask()[i] >= 0)
10611             NumV1OddIndices += i % 2;
10612         if (NumV2OddIndices < NumV1OddIndices)
10613           return DAG.getCommutedVectorShuffle(*SVOp);
10614       }
10615     }
10616   }
10617
10618   // For each vector width, delegate to a specialized lowering routine.
10619   if (VT.getSizeInBits() == 128)
10620     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10621
10622   if (VT.getSizeInBits() == 256)
10623     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10624
10625   // Force AVX-512 vectors to be scalarized for now.
10626   // FIXME: Implement AVX-512 support!
10627   if (VT.getSizeInBits() == 512)
10628     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10629
10630   llvm_unreachable("Unimplemented!");
10631 }
10632
10633 // This function assumes its argument is a BUILD_VECTOR of constants or
10634 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10635 // true.
10636 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10637                                     unsigned &MaskValue) {
10638   MaskValue = 0;
10639   unsigned NumElems = BuildVector->getNumOperands();
10640   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10641   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10642   unsigned NumElemsInLane = NumElems / NumLanes;
10643
10644   // Blend for v16i16 should be symetric for the both lanes.
10645   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10646     SDValue EltCond = BuildVector->getOperand(i);
10647     SDValue SndLaneEltCond =
10648         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10649
10650     int Lane1Cond = -1, Lane2Cond = -1;
10651     if (isa<ConstantSDNode>(EltCond))
10652       Lane1Cond = !isZero(EltCond);
10653     if (isa<ConstantSDNode>(SndLaneEltCond))
10654       Lane2Cond = !isZero(SndLaneEltCond);
10655
10656     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10657       // Lane1Cond != 0, means we want the first argument.
10658       // Lane1Cond == 0, means we want the second argument.
10659       // The encoding of this argument is 0 for the first argument, 1
10660       // for the second. Therefore, invert the condition.
10661       MaskValue |= !Lane1Cond << i;
10662     else if (Lane1Cond < 0)
10663       MaskValue |= !Lane2Cond << i;
10664     else
10665       return false;
10666   }
10667   return true;
10668 }
10669
10670 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10671 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10672                                            const X86Subtarget *Subtarget,
10673                                            SelectionDAG &DAG) {
10674   SDValue Cond = Op.getOperand(0);
10675   SDValue LHS = Op.getOperand(1);
10676   SDValue RHS = Op.getOperand(2);
10677   SDLoc dl(Op);
10678   MVT VT = Op.getSimpleValueType();
10679
10680   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10681     return SDValue();
10682   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10683
10684   // Only non-legal VSELECTs reach this lowering, convert those into generic
10685   // shuffles and re-use the shuffle lowering path for blends.
10686   SmallVector<int, 32> Mask;
10687   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10688     SDValue CondElt = CondBV->getOperand(i);
10689     Mask.push_back(
10690         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10691   }
10692   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10693 }
10694
10695 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10696   // A vselect where all conditions and data are constants can be optimized into
10697   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10698   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10699       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10700       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10701     return SDValue();
10702
10703   // Try to lower this to a blend-style vector shuffle. This can handle all
10704   // constant condition cases.
10705   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10706     return BlendOp;
10707
10708   // Variable blends are only legal from SSE4.1 onward.
10709   if (!Subtarget->hasSSE41())
10710     return SDValue();
10711
10712   // Only some types will be legal on some subtargets. If we can emit a legal
10713   // VSELECT-matching blend, return Op, and but if we need to expand, return
10714   // a null value.
10715   switch (Op.getSimpleValueType().SimpleTy) {
10716   default:
10717     // Most of the vector types have blends past SSE4.1.
10718     return Op;
10719
10720   case MVT::v32i8:
10721     // The byte blends for AVX vectors were introduced only in AVX2.
10722     if (Subtarget->hasAVX2())
10723       return Op;
10724
10725     return SDValue();
10726
10727   case MVT::v8i16:
10728   case MVT::v16i16:
10729     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10730     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10731       return Op;
10732
10733     // FIXME: We should custom lower this by fixing the condition and using i8
10734     // blends.
10735     return SDValue();
10736   }
10737 }
10738
10739 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10740   MVT VT = Op.getSimpleValueType();
10741   SDLoc dl(Op);
10742
10743   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10744     return SDValue();
10745
10746   if (VT.getSizeInBits() == 8) {
10747     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10748                                   Op.getOperand(0), Op.getOperand(1));
10749     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10750                                   DAG.getValueType(VT));
10751     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10752   }
10753
10754   if (VT.getSizeInBits() == 16) {
10755     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10756     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10757     if (Idx == 0)
10758       return DAG.getNode(
10759           ISD::TRUNCATE, dl, MVT::i16,
10760           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10761                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10762                       Op.getOperand(1)));
10763     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10764                                   Op.getOperand(0), Op.getOperand(1));
10765     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10766                                   DAG.getValueType(VT));
10767     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10768   }
10769
10770   if (VT == MVT::f32) {
10771     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10772     // the result back to FR32 register. It's only worth matching if the
10773     // result has a single use which is a store or a bitcast to i32.  And in
10774     // the case of a store, it's not worth it if the index is a constant 0,
10775     // because a MOVSSmr can be used instead, which is smaller and faster.
10776     if (!Op.hasOneUse())
10777       return SDValue();
10778     SDNode *User = *Op.getNode()->use_begin();
10779     if ((User->getOpcode() != ISD::STORE ||
10780          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10781           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10782         (User->getOpcode() != ISD::BITCAST ||
10783          User->getValueType(0) != MVT::i32))
10784       return SDValue();
10785     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10786                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10787                                   Op.getOperand(1));
10788     return DAG.getBitcast(MVT::f32, Extract);
10789   }
10790
10791   if (VT == MVT::i32 || VT == MVT::i64) {
10792     // ExtractPS/pextrq works with constant index.
10793     if (isa<ConstantSDNode>(Op.getOperand(1)))
10794       return Op;
10795   }
10796   return SDValue();
10797 }
10798
10799 /// Extract one bit from mask vector, like v16i1 or v8i1.
10800 /// AVX-512 feature.
10801 SDValue
10802 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10803   SDValue Vec = Op.getOperand(0);
10804   SDLoc dl(Vec);
10805   MVT VecVT = Vec.getSimpleValueType();
10806   SDValue Idx = Op.getOperand(1);
10807   MVT EltVT = Op.getSimpleValueType();
10808
10809   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10810   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10811          "Unexpected vector type in ExtractBitFromMaskVector");
10812
10813   // variable index can't be handled in mask registers,
10814   // extend vector to VR512
10815   if (!isa<ConstantSDNode>(Idx)) {
10816     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10817     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10818     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10819                               ExtVT.getVectorElementType(), Ext, Idx);
10820     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10821   }
10822
10823   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10824   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10825   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10826     rc = getRegClassFor(MVT::v16i1);
10827   unsigned MaxSift = rc->getSize()*8 - 1;
10828   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10829                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10830   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10831                     DAG.getConstant(MaxSift, dl, MVT::i8));
10832   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10833                        DAG.getIntPtrConstant(0, dl));
10834 }
10835
10836 SDValue
10837 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10838                                            SelectionDAG &DAG) const {
10839   SDLoc dl(Op);
10840   SDValue Vec = Op.getOperand(0);
10841   MVT VecVT = Vec.getSimpleValueType();
10842   SDValue Idx = Op.getOperand(1);
10843
10844   if (Op.getSimpleValueType() == MVT::i1)
10845     return ExtractBitFromMaskVector(Op, DAG);
10846
10847   if (!isa<ConstantSDNode>(Idx)) {
10848     if (VecVT.is512BitVector() ||
10849         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10850          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10851
10852       MVT MaskEltVT =
10853         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10854       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10855                                     MaskEltVT.getSizeInBits());
10856
10857       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10858       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10859                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10860                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10861       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10862       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10863                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10864     }
10865     return SDValue();
10866   }
10867
10868   // If this is a 256-bit vector result, first extract the 128-bit vector and
10869   // then extract the element from the 128-bit vector.
10870   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10871
10872     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10873     // Get the 128-bit vector.
10874     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10875     MVT EltVT = VecVT.getVectorElementType();
10876
10877     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10878
10879     //if (IdxVal >= NumElems/2)
10880     //  IdxVal -= NumElems/2;
10881     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10882     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10883                        DAG.getConstant(IdxVal, dl, MVT::i32));
10884   }
10885
10886   assert(VecVT.is128BitVector() && "Unexpected vector length");
10887
10888   if (Subtarget->hasSSE41())
10889     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10890       return Res;
10891
10892   MVT VT = Op.getSimpleValueType();
10893   // TODO: handle v16i8.
10894   if (VT.getSizeInBits() == 16) {
10895     SDValue Vec = Op.getOperand(0);
10896     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10897     if (Idx == 0)
10898       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10899                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10900                                      DAG.getBitcast(MVT::v4i32, Vec),
10901                                      Op.getOperand(1)));
10902     // Transform it so it match pextrw which produces a 32-bit result.
10903     MVT EltVT = MVT::i32;
10904     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10905                                   Op.getOperand(0), Op.getOperand(1));
10906     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10907                                   DAG.getValueType(VT));
10908     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10909   }
10910
10911   if (VT.getSizeInBits() == 32) {
10912     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10913     if (Idx == 0)
10914       return Op;
10915
10916     // SHUFPS the element to the lowest double word, then movss.
10917     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10918     MVT VVT = Op.getOperand(0).getSimpleValueType();
10919     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10920                                        DAG.getUNDEF(VVT), Mask);
10921     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10922                        DAG.getIntPtrConstant(0, dl));
10923   }
10924
10925   if (VT.getSizeInBits() == 64) {
10926     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10927     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10928     //        to match extract_elt for f64.
10929     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10930     if (Idx == 0)
10931       return Op;
10932
10933     // UNPCKHPD the element to the lowest double word, then movsd.
10934     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10935     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10936     int Mask[2] = { 1, -1 };
10937     MVT VVT = Op.getOperand(0).getSimpleValueType();
10938     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10939                                        DAG.getUNDEF(VVT), Mask);
10940     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10941                        DAG.getIntPtrConstant(0, dl));
10942   }
10943
10944   return SDValue();
10945 }
10946
10947 /// Insert one bit to mask vector, like v16i1 or v8i1.
10948 /// AVX-512 feature.
10949 SDValue
10950 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10951   SDLoc dl(Op);
10952   SDValue Vec = Op.getOperand(0);
10953   SDValue Elt = Op.getOperand(1);
10954   SDValue Idx = Op.getOperand(2);
10955   MVT VecVT = Vec.getSimpleValueType();
10956
10957   if (!isa<ConstantSDNode>(Idx)) {
10958     // Non constant index. Extend source and destination,
10959     // insert element and then truncate the result.
10960     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10961     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10962     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10963       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10964       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10965     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10966   }
10967
10968   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10969   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10970   if (IdxVal)
10971     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10972                            DAG.getConstant(IdxVal, dl, MVT::i8));
10973   if (Vec.getOpcode() == ISD::UNDEF)
10974     return EltInVec;
10975   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10976 }
10977
10978 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10979                                                   SelectionDAG &DAG) const {
10980   MVT VT = Op.getSimpleValueType();
10981   MVT EltVT = VT.getVectorElementType();
10982
10983   if (EltVT == MVT::i1)
10984     return InsertBitToMaskVector(Op, DAG);
10985
10986   SDLoc dl(Op);
10987   SDValue N0 = Op.getOperand(0);
10988   SDValue N1 = Op.getOperand(1);
10989   SDValue N2 = Op.getOperand(2);
10990   if (!isa<ConstantSDNode>(N2))
10991     return SDValue();
10992   auto *N2C = cast<ConstantSDNode>(N2);
10993   unsigned IdxVal = N2C->getZExtValue();
10994
10995   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10996   // into that, and then insert the subvector back into the result.
10997   if (VT.is256BitVector() || VT.is512BitVector()) {
10998     // With a 256-bit vector, we can insert into the zero element efficiently
10999     // using a blend if we have AVX or AVX2 and the right data type.
11000     if (VT.is256BitVector() && IdxVal == 0) {
11001       // TODO: It is worthwhile to cast integer to floating point and back
11002       // and incur a domain crossing penalty if that's what we'll end up
11003       // doing anyway after extracting to a 128-bit vector.
11004       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11005           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11006         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11007         N2 = DAG.getIntPtrConstant(1, dl);
11008         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11009       }
11010     }
11011
11012     // Get the desired 128-bit vector chunk.
11013     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11014
11015     // Insert the element into the desired chunk.
11016     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11017     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11018
11019     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11020                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11021
11022     // Insert the changed part back into the bigger vector
11023     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11024   }
11025   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11026
11027   if (Subtarget->hasSSE41()) {
11028     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11029       unsigned Opc;
11030       if (VT == MVT::v8i16) {
11031         Opc = X86ISD::PINSRW;
11032       } else {
11033         assert(VT == MVT::v16i8);
11034         Opc = X86ISD::PINSRB;
11035       }
11036
11037       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11038       // argument.
11039       if (N1.getValueType() != MVT::i32)
11040         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11041       if (N2.getValueType() != MVT::i32)
11042         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11043       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11044     }
11045
11046     if (EltVT == MVT::f32) {
11047       // Bits [7:6] of the constant are the source select. This will always be
11048       //   zero here. The DAG Combiner may combine an extract_elt index into
11049       //   these bits. For example (insert (extract, 3), 2) could be matched by
11050       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11051       // Bits [5:4] of the constant are the destination select. This is the
11052       //   value of the incoming immediate.
11053       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11054       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11055
11056       const Function *F = DAG.getMachineFunction().getFunction();
11057       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11058       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11059         // If this is an insertion of 32-bits into the low 32-bits of
11060         // a vector, we prefer to generate a blend with immediate rather
11061         // than an insertps. Blends are simpler operations in hardware and so
11062         // will always have equal or better performance than insertps.
11063         // But if optimizing for size and there's a load folding opportunity,
11064         // generate insertps because blendps does not have a 32-bit memory
11065         // operand form.
11066         N2 = DAG.getIntPtrConstant(1, dl);
11067         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11068         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11069       }
11070       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11071       // Create this as a scalar to vector..
11072       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11073       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11074     }
11075
11076     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11077       // PINSR* works with constant index.
11078       return Op;
11079     }
11080   }
11081
11082   if (EltVT == MVT::i8)
11083     return SDValue();
11084
11085   if (EltVT.getSizeInBits() == 16) {
11086     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11087     // as its second argument.
11088     if (N1.getValueType() != MVT::i32)
11089       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11090     if (N2.getValueType() != MVT::i32)
11091       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11092     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11093   }
11094   return SDValue();
11095 }
11096
11097 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11098   SDLoc dl(Op);
11099   MVT OpVT = Op.getSimpleValueType();
11100
11101   // If this is a 256-bit vector result, first insert into a 128-bit
11102   // vector and then insert into the 256-bit vector.
11103   if (!OpVT.is128BitVector()) {
11104     // Insert into a 128-bit vector.
11105     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11106     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11107                                  OpVT.getVectorNumElements() / SizeFactor);
11108
11109     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11110
11111     // Insert the 128-bit vector.
11112     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11113   }
11114
11115   if (OpVT == MVT::v1i64 &&
11116       Op.getOperand(0).getValueType() == MVT::i64)
11117     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11118
11119   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11120   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11121   return DAG.getBitcast(
11122       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11123 }
11124
11125 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11126 // a simple subregister reference or explicit instructions to grab
11127 // upper bits of a vector.
11128 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11129                                       SelectionDAG &DAG) {
11130   SDLoc dl(Op);
11131   SDValue In =  Op.getOperand(0);
11132   SDValue Idx = Op.getOperand(1);
11133   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11134   MVT ResVT   = Op.getSimpleValueType();
11135   MVT InVT    = In.getSimpleValueType();
11136
11137   if (Subtarget->hasFp256()) {
11138     if (ResVT.is128BitVector() &&
11139         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11140         isa<ConstantSDNode>(Idx)) {
11141       return Extract128BitVector(In, IdxVal, DAG, dl);
11142     }
11143     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11144         isa<ConstantSDNode>(Idx)) {
11145       return Extract256BitVector(In, IdxVal, DAG, dl);
11146     }
11147   }
11148   return SDValue();
11149 }
11150
11151 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11152 // simple superregister reference or explicit instructions to insert
11153 // the upper bits of a vector.
11154 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11155                                      SelectionDAG &DAG) {
11156   if (!Subtarget->hasAVX())
11157     return SDValue();
11158
11159   SDLoc dl(Op);
11160   SDValue Vec = Op.getOperand(0);
11161   SDValue SubVec = Op.getOperand(1);
11162   SDValue Idx = Op.getOperand(2);
11163
11164   if (!isa<ConstantSDNode>(Idx))
11165     return SDValue();
11166
11167   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11168   MVT OpVT = Op.getSimpleValueType();
11169   MVT SubVecVT = SubVec.getSimpleValueType();
11170
11171   // Fold two 16-byte subvector loads into one 32-byte load:
11172   // (insert_subvector (insert_subvector undef, (load addr), 0),
11173   //                   (load addr + 16), Elts/2)
11174   // --> load32 addr
11175   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11176       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11177       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11178       !Subtarget->isUnalignedMem32Slow()) {
11179     SDValue SubVec2 = Vec.getOperand(1);
11180     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11181       if (Idx2->getZExtValue() == 0) {
11182         SDValue Ops[] = { SubVec2, SubVec };
11183         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11184           return Ld;
11185       }
11186     }
11187   }
11188
11189   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11190       SubVecVT.is128BitVector())
11191     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11192
11193   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11194     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11195
11196   if (OpVT.getVectorElementType() == MVT::i1) {
11197     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11198       return Op;
11199     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11200     SDValue Undef = DAG.getUNDEF(OpVT);
11201     unsigned NumElems = OpVT.getVectorNumElements();
11202     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11203
11204     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11205       // Zero upper bits of the Vec
11206       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11207       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11208
11209       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11210                                  SubVec, ZeroIdx);
11211       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11212       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11213     }
11214     if (IdxVal == 0) {
11215       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11216                                  SubVec, ZeroIdx);
11217       // Zero upper bits of the Vec2
11218       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11219       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11220       // Zero lower bits of the Vec
11221       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11222       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11223       // Merge them together
11224       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11225     }
11226   }
11227   return SDValue();
11228 }
11229
11230 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11231 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11232 // one of the above mentioned nodes. It has to be wrapped because otherwise
11233 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11234 // be used to form addressing mode. These wrapped nodes will be selected
11235 // into MOV32ri.
11236 SDValue
11237 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11238   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11239
11240   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11241   // global base reg.
11242   unsigned char OpFlag = 0;
11243   unsigned WrapperKind = X86ISD::Wrapper;
11244   CodeModel::Model M = DAG.getTarget().getCodeModel();
11245
11246   if (Subtarget->isPICStyleRIPRel() &&
11247       (M == CodeModel::Small || M == CodeModel::Kernel))
11248     WrapperKind = X86ISD::WrapperRIP;
11249   else if (Subtarget->isPICStyleGOT())
11250     OpFlag = X86II::MO_GOTOFF;
11251   else if (Subtarget->isPICStyleStubPIC())
11252     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11253
11254   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11255                                              CP->getAlignment(),
11256                                              CP->getOffset(), OpFlag);
11257   SDLoc DL(CP);
11258   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11259   // With PIC, the address is actually $g + Offset.
11260   if (OpFlag) {
11261     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11262                          DAG.getNode(X86ISD::GlobalBaseReg,
11263                                      SDLoc(), getPointerTy()),
11264                          Result);
11265   }
11266
11267   return Result;
11268 }
11269
11270 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11271   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11272
11273   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11274   // global base reg.
11275   unsigned char OpFlag = 0;
11276   unsigned WrapperKind = X86ISD::Wrapper;
11277   CodeModel::Model M = DAG.getTarget().getCodeModel();
11278
11279   if (Subtarget->isPICStyleRIPRel() &&
11280       (M == CodeModel::Small || M == CodeModel::Kernel))
11281     WrapperKind = X86ISD::WrapperRIP;
11282   else if (Subtarget->isPICStyleGOT())
11283     OpFlag = X86II::MO_GOTOFF;
11284   else if (Subtarget->isPICStyleStubPIC())
11285     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11286
11287   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11288                                           OpFlag);
11289   SDLoc DL(JT);
11290   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11291
11292   // With PIC, the address is actually $g + Offset.
11293   if (OpFlag)
11294     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11295                          DAG.getNode(X86ISD::GlobalBaseReg,
11296                                      SDLoc(), getPointerTy()),
11297                          Result);
11298
11299   return Result;
11300 }
11301
11302 SDValue
11303 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11304   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11305
11306   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11307   // global base reg.
11308   unsigned char OpFlag = 0;
11309   unsigned WrapperKind = X86ISD::Wrapper;
11310   CodeModel::Model M = DAG.getTarget().getCodeModel();
11311
11312   if (Subtarget->isPICStyleRIPRel() &&
11313       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11314     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11315       OpFlag = X86II::MO_GOTPCREL;
11316     WrapperKind = X86ISD::WrapperRIP;
11317   } else if (Subtarget->isPICStyleGOT()) {
11318     OpFlag = X86II::MO_GOT;
11319   } else if (Subtarget->isPICStyleStubPIC()) {
11320     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11321   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11322     OpFlag = X86II::MO_DARWIN_NONLAZY;
11323   }
11324
11325   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11326
11327   SDLoc DL(Op);
11328   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11329
11330   // With PIC, the address is actually $g + Offset.
11331   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11332       !Subtarget->is64Bit()) {
11333     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11334                          DAG.getNode(X86ISD::GlobalBaseReg,
11335                                      SDLoc(), getPointerTy()),
11336                          Result);
11337   }
11338
11339   // For symbols that require a load from a stub to get the address, emit the
11340   // load.
11341   if (isGlobalStubReference(OpFlag))
11342     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11343                          MachinePointerInfo::getGOT(), false, false, false, 0);
11344
11345   return Result;
11346 }
11347
11348 SDValue
11349 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11350   // Create the TargetBlockAddressAddress node.
11351   unsigned char OpFlags =
11352     Subtarget->ClassifyBlockAddressReference();
11353   CodeModel::Model M = DAG.getTarget().getCodeModel();
11354   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11355   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11356   SDLoc dl(Op);
11357   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11358                                              OpFlags);
11359
11360   if (Subtarget->isPICStyleRIPRel() &&
11361       (M == CodeModel::Small || M == CodeModel::Kernel))
11362     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11363   else
11364     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11365
11366   // With PIC, the address is actually $g + Offset.
11367   if (isGlobalRelativeToPICBase(OpFlags)) {
11368     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11369                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11370                          Result);
11371   }
11372
11373   return Result;
11374 }
11375
11376 SDValue
11377 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11378                                       int64_t Offset, SelectionDAG &DAG) const {
11379   // Create the TargetGlobalAddress node, folding in the constant
11380   // offset if it is legal.
11381   unsigned char OpFlags =
11382       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11383   CodeModel::Model M = DAG.getTarget().getCodeModel();
11384   SDValue Result;
11385   if (OpFlags == X86II::MO_NO_FLAG &&
11386       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11387     // A direct static reference to a global.
11388     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11389     Offset = 0;
11390   } else {
11391     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11392   }
11393
11394   if (Subtarget->isPICStyleRIPRel() &&
11395       (M == CodeModel::Small || M == CodeModel::Kernel))
11396     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11397   else
11398     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11399
11400   // With PIC, the address is actually $g + Offset.
11401   if (isGlobalRelativeToPICBase(OpFlags)) {
11402     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11403                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11404                          Result);
11405   }
11406
11407   // For globals that require a load from a stub to get the address, emit the
11408   // load.
11409   if (isGlobalStubReference(OpFlags))
11410     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11411                          MachinePointerInfo::getGOT(), false, false, false, 0);
11412
11413   // If there was a non-zero offset that we didn't fold, create an explicit
11414   // addition for it.
11415   if (Offset != 0)
11416     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11417                          DAG.getConstant(Offset, dl, getPointerTy()));
11418
11419   return Result;
11420 }
11421
11422 SDValue
11423 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11424   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11425   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11426   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11427 }
11428
11429 static SDValue
11430 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11431            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11432            unsigned char OperandFlags, bool LocalDynamic = false) {
11433   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11434   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11435   SDLoc dl(GA);
11436   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11437                                            GA->getValueType(0),
11438                                            GA->getOffset(),
11439                                            OperandFlags);
11440
11441   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11442                                            : X86ISD::TLSADDR;
11443
11444   if (InFlag) {
11445     SDValue Ops[] = { Chain,  TGA, *InFlag };
11446     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11447   } else {
11448     SDValue Ops[]  = { Chain, TGA };
11449     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11450   }
11451
11452   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11453   MFI->setAdjustsStack(true);
11454   MFI->setHasCalls(true);
11455
11456   SDValue Flag = Chain.getValue(1);
11457   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11458 }
11459
11460 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11461 static SDValue
11462 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11463                                 const EVT PtrVT) {
11464   SDValue InFlag;
11465   SDLoc dl(GA);  // ? function entry point might be better
11466   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11467                                    DAG.getNode(X86ISD::GlobalBaseReg,
11468                                                SDLoc(), PtrVT), InFlag);
11469   InFlag = Chain.getValue(1);
11470
11471   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11472 }
11473
11474 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11475 static SDValue
11476 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11477                                 const EVT PtrVT) {
11478   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11479                     X86::RAX, X86II::MO_TLSGD);
11480 }
11481
11482 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11483                                            SelectionDAG &DAG,
11484                                            const EVT PtrVT,
11485                                            bool is64Bit) {
11486   SDLoc dl(GA);
11487
11488   // Get the start address of the TLS block for this module.
11489   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11490       .getInfo<X86MachineFunctionInfo>();
11491   MFI->incNumLocalDynamicTLSAccesses();
11492
11493   SDValue Base;
11494   if (is64Bit) {
11495     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11496                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11497   } else {
11498     SDValue InFlag;
11499     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11500         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11501     InFlag = Chain.getValue(1);
11502     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11503                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11504   }
11505
11506   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11507   // of Base.
11508
11509   // Build x@dtpoff.
11510   unsigned char OperandFlags = X86II::MO_DTPOFF;
11511   unsigned WrapperKind = X86ISD::Wrapper;
11512   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11513                                            GA->getValueType(0),
11514                                            GA->getOffset(), OperandFlags);
11515   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11516
11517   // Add x@dtpoff with the base.
11518   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11519 }
11520
11521 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11522 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11523                                    const EVT PtrVT, TLSModel::Model model,
11524                                    bool is64Bit, bool isPIC) {
11525   SDLoc dl(GA);
11526
11527   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11528   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11529                                                          is64Bit ? 257 : 256));
11530
11531   SDValue ThreadPointer =
11532       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11533                   MachinePointerInfo(Ptr), false, false, false, 0);
11534
11535   unsigned char OperandFlags = 0;
11536   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11537   // initialexec.
11538   unsigned WrapperKind = X86ISD::Wrapper;
11539   if (model == TLSModel::LocalExec) {
11540     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11541   } else if (model == TLSModel::InitialExec) {
11542     if (is64Bit) {
11543       OperandFlags = X86II::MO_GOTTPOFF;
11544       WrapperKind = X86ISD::WrapperRIP;
11545     } else {
11546       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11547     }
11548   } else {
11549     llvm_unreachable("Unexpected model");
11550   }
11551
11552   // emit "addl x@ntpoff,%eax" (local exec)
11553   // or "addl x@indntpoff,%eax" (initial exec)
11554   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11555   SDValue TGA =
11556       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11557                                  GA->getOffset(), OperandFlags);
11558   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11559
11560   if (model == TLSModel::InitialExec) {
11561     if (isPIC && !is64Bit) {
11562       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11563                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11564                            Offset);
11565     }
11566
11567     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11568                          MachinePointerInfo::getGOT(), false, false, false, 0);
11569   }
11570
11571   // The address of the thread local variable is the add of the thread
11572   // pointer with the offset of the variable.
11573   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11574 }
11575
11576 SDValue
11577 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11578
11579   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11580   const GlobalValue *GV = GA->getGlobal();
11581
11582   if (Subtarget->isTargetELF()) {
11583     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11584     switch (model) {
11585       case TLSModel::GeneralDynamic:
11586         if (Subtarget->is64Bit())
11587           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11588         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11589       case TLSModel::LocalDynamic:
11590         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11591                                            Subtarget->is64Bit());
11592       case TLSModel::InitialExec:
11593       case TLSModel::LocalExec:
11594         return LowerToTLSExecModel(
11595             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11596             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11597     }
11598     llvm_unreachable("Unknown TLS model.");
11599   }
11600
11601   if (Subtarget->isTargetDarwin()) {
11602     // Darwin only has one model of TLS.  Lower to that.
11603     unsigned char OpFlag = 0;
11604     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11605                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11606
11607     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11608     // global base reg.
11609     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11610                  !Subtarget->is64Bit();
11611     if (PIC32)
11612       OpFlag = X86II::MO_TLVP_PIC_BASE;
11613     else
11614       OpFlag = X86II::MO_TLVP;
11615     SDLoc DL(Op);
11616     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11617                                                 GA->getValueType(0),
11618                                                 GA->getOffset(), OpFlag);
11619     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11620
11621     // With PIC32, the address is actually $g + Offset.
11622     if (PIC32)
11623       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11624                            DAG.getNode(X86ISD::GlobalBaseReg,
11625                                        SDLoc(), getPointerTy()),
11626                            Offset);
11627
11628     // Lowering the machine isd will make sure everything is in the right
11629     // location.
11630     SDValue Chain = DAG.getEntryNode();
11631     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11632     SDValue Args[] = { Chain, Offset };
11633     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11634
11635     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11636     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11637     MFI->setAdjustsStack(true);
11638
11639     // And our return value (tls address) is in the standard call return value
11640     // location.
11641     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11642     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11643                               Chain.getValue(1));
11644   }
11645
11646   if (Subtarget->isTargetKnownWindowsMSVC() ||
11647       Subtarget->isTargetWindowsGNU()) {
11648     // Just use the implicit TLS architecture
11649     // Need to generate someting similar to:
11650     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11651     //                                  ; from TEB
11652     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11653     //   mov     rcx, qword [rdx+rcx*8]
11654     //   mov     eax, .tls$:tlsvar
11655     //   [rax+rcx] contains the address
11656     // Windows 64bit: gs:0x58
11657     // Windows 32bit: fs:__tls_array
11658
11659     SDLoc dl(GA);
11660     SDValue Chain = DAG.getEntryNode();
11661
11662     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11663     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11664     // use its literal value of 0x2C.
11665     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11666                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11667                                                              256)
11668                                         : Type::getInt32PtrTy(*DAG.getContext(),
11669                                                               257));
11670
11671     SDValue TlsArray =
11672         Subtarget->is64Bit()
11673             ? DAG.getIntPtrConstant(0x58, dl)
11674             : (Subtarget->isTargetWindowsGNU()
11675                    ? DAG.getIntPtrConstant(0x2C, dl)
11676                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11677
11678     SDValue ThreadPointer =
11679         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11680                     MachinePointerInfo(Ptr), false, false, false, 0);
11681
11682     SDValue res;
11683     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11684       res = ThreadPointer;
11685     } else {
11686       // Load the _tls_index variable
11687       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11688       if (Subtarget->is64Bit())
11689         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11690                              MachinePointerInfo(), MVT::i32, false, false,
11691                              false, 0);
11692       else
11693         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11694                           false, false, false, 0);
11695
11696       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11697                                       getPointerTy());
11698       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11699
11700       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11701     }
11702
11703     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11704                       false, false, false, 0);
11705
11706     // Get the offset of start of .tls section
11707     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11708                                              GA->getValueType(0),
11709                                              GA->getOffset(), X86II::MO_SECREL);
11710     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11711
11712     // The address of the thread local variable is the add of the thread
11713     // pointer with the offset of the variable.
11714     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11715   }
11716
11717   llvm_unreachable("TLS not implemented for this target.");
11718 }
11719
11720 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11721 /// and take a 2 x i32 value to shift plus a shift amount.
11722 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11723   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11724   MVT VT = Op.getSimpleValueType();
11725   unsigned VTBits = VT.getSizeInBits();
11726   SDLoc dl(Op);
11727   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11728   SDValue ShOpLo = Op.getOperand(0);
11729   SDValue ShOpHi = Op.getOperand(1);
11730   SDValue ShAmt  = Op.getOperand(2);
11731   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11732   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11733   // during isel.
11734   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11735                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11736   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11737                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11738                        : DAG.getConstant(0, dl, VT);
11739
11740   SDValue Tmp2, Tmp3;
11741   if (Op.getOpcode() == ISD::SHL_PARTS) {
11742     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11743     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11744   } else {
11745     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11746     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11747   }
11748
11749   // If the shift amount is larger or equal than the width of a part we can't
11750   // rely on the results of shld/shrd. Insert a test and select the appropriate
11751   // values for large shift amounts.
11752   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11753                                 DAG.getConstant(VTBits, dl, MVT::i8));
11754   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11755                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11756
11757   SDValue Hi, Lo;
11758   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11759   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11760   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11761
11762   if (Op.getOpcode() == ISD::SHL_PARTS) {
11763     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11764     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11765   } else {
11766     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11767     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11768   }
11769
11770   SDValue Ops[2] = { Lo, Hi };
11771   return DAG.getMergeValues(Ops, dl);
11772 }
11773
11774 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11775                                            SelectionDAG &DAG) const {
11776   SDValue Src = Op.getOperand(0);
11777   MVT SrcVT = Src.getSimpleValueType();
11778   MVT VT = Op.getSimpleValueType();
11779   SDLoc dl(Op);
11780
11781   if (SrcVT.isVector()) {
11782     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11783       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11784                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11785                          DAG.getUNDEF(SrcVT)));
11786     }
11787     if (SrcVT.getVectorElementType() == MVT::i1) {
11788       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11789       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11790                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11791     }
11792     return SDValue();
11793   }
11794
11795   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11796          "Unknown SINT_TO_FP to lower!");
11797
11798   // These are really Legal; return the operand so the caller accepts it as
11799   // Legal.
11800   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11801     return Op;
11802   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11803       Subtarget->is64Bit()) {
11804     return Op;
11805   }
11806
11807   unsigned Size = SrcVT.getSizeInBits()/8;
11808   MachineFunction &MF = DAG.getMachineFunction();
11809   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11810   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11811   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11812                                StackSlot,
11813                                MachinePointerInfo::getFixedStack(SSFI),
11814                                false, false, 0);
11815   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11816 }
11817
11818 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11819                                      SDValue StackSlot,
11820                                      SelectionDAG &DAG) const {
11821   // Build the FILD
11822   SDLoc DL(Op);
11823   SDVTList Tys;
11824   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11825   if (useSSE)
11826     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11827   else
11828     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11829
11830   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11831
11832   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11833   MachineMemOperand *MMO;
11834   if (FI) {
11835     int SSFI = FI->getIndex();
11836     MMO =
11837       DAG.getMachineFunction()
11838       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11839                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11840   } else {
11841     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11842     StackSlot = StackSlot.getOperand(1);
11843   }
11844   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11845   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11846                                            X86ISD::FILD, DL,
11847                                            Tys, Ops, SrcVT, MMO);
11848
11849   if (useSSE) {
11850     Chain = Result.getValue(1);
11851     SDValue InFlag = Result.getValue(2);
11852
11853     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11854     // shouldn't be necessary except that RFP cannot be live across
11855     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11856     MachineFunction &MF = DAG.getMachineFunction();
11857     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11858     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11859     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11860     Tys = DAG.getVTList(MVT::Other);
11861     SDValue Ops[] = {
11862       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11863     };
11864     MachineMemOperand *MMO =
11865       DAG.getMachineFunction()
11866       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11867                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11868
11869     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11870                                     Ops, Op.getValueType(), MMO);
11871     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11872                          MachinePointerInfo::getFixedStack(SSFI),
11873                          false, false, false, 0);
11874   }
11875
11876   return Result;
11877 }
11878
11879 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11880 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11881                                                SelectionDAG &DAG) const {
11882   // This algorithm is not obvious. Here it is what we're trying to output:
11883   /*
11884      movq       %rax,  %xmm0
11885      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11886      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11887      #ifdef __SSE3__
11888        haddpd   %xmm0, %xmm0
11889      #else
11890        pshufd   $0x4e, %xmm0, %xmm1
11891        addpd    %xmm1, %xmm0
11892      #endif
11893   */
11894
11895   SDLoc dl(Op);
11896   LLVMContext *Context = DAG.getContext();
11897
11898   // Build some magic constants.
11899   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11900   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11901   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11902
11903   SmallVector<Constant*,2> CV1;
11904   CV1.push_back(
11905     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11906                                       APInt(64, 0x4330000000000000ULL))));
11907   CV1.push_back(
11908     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11909                                       APInt(64, 0x4530000000000000ULL))));
11910   Constant *C1 = ConstantVector::get(CV1);
11911   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11912
11913   // Load the 64-bit value into an XMM register.
11914   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11915                             Op.getOperand(0));
11916   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11917                               MachinePointerInfo::getConstantPool(),
11918                               false, false, false, 16);
11919   SDValue Unpck1 =
11920       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11921
11922   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11923                               MachinePointerInfo::getConstantPool(),
11924                               false, false, false, 16);
11925   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11926   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11927   SDValue Result;
11928
11929   if (Subtarget->hasSSE3()) {
11930     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11931     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11932   } else {
11933     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11934     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11935                                            S2F, 0x4E, DAG);
11936     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11937                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11938   }
11939
11940   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11941                      DAG.getIntPtrConstant(0, dl));
11942 }
11943
11944 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11945 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11946                                                SelectionDAG &DAG) const {
11947   SDLoc dl(Op);
11948   // FP constant to bias correct the final result.
11949   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11950                                    MVT::f64);
11951
11952   // Load the 32-bit value into an XMM register.
11953   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11954                              Op.getOperand(0));
11955
11956   // Zero out the upper parts of the register.
11957   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11958
11959   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11960                      DAG.getBitcast(MVT::v2f64, Load),
11961                      DAG.getIntPtrConstant(0, dl));
11962
11963   // Or the load with the bias.
11964   SDValue Or = DAG.getNode(
11965       ISD::OR, dl, MVT::v2i64,
11966       DAG.getBitcast(MVT::v2i64,
11967                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
11968       DAG.getBitcast(MVT::v2i64,
11969                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
11970   Or =
11971       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11972                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
11973
11974   // Subtract the bias.
11975   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11976
11977   // Handle final rounding.
11978   EVT DestVT = Op.getValueType();
11979
11980   if (DestVT.bitsLT(MVT::f64))
11981     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11982                        DAG.getIntPtrConstant(0, dl));
11983   if (DestVT.bitsGT(MVT::f64))
11984     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11985
11986   // Handle final rounding.
11987   return Sub;
11988 }
11989
11990 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11991                                      const X86Subtarget &Subtarget) {
11992   // The algorithm is the following:
11993   // #ifdef __SSE4_1__
11994   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11995   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11996   //                                 (uint4) 0x53000000, 0xaa);
11997   // #else
11998   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11999   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12000   // #endif
12001   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12002   //     return (float4) lo + fhi;
12003
12004   SDLoc DL(Op);
12005   SDValue V = Op->getOperand(0);
12006   EVT VecIntVT = V.getValueType();
12007   bool Is128 = VecIntVT == MVT::v4i32;
12008   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12009   // If we convert to something else than the supported type, e.g., to v4f64,
12010   // abort early.
12011   if (VecFloatVT != Op->getValueType(0))
12012     return SDValue();
12013
12014   unsigned NumElts = VecIntVT.getVectorNumElements();
12015   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12016          "Unsupported custom type");
12017   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12018
12019   // In the #idef/#else code, we have in common:
12020   // - The vector of constants:
12021   // -- 0x4b000000
12022   // -- 0x53000000
12023   // - A shift:
12024   // -- v >> 16
12025
12026   // Create the splat vector for 0x4b000000.
12027   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12028   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12029                            CstLow, CstLow, CstLow, CstLow};
12030   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12031                                   makeArrayRef(&CstLowArray[0], NumElts));
12032   // Create the splat vector for 0x53000000.
12033   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12034   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12035                             CstHigh, CstHigh, CstHigh, CstHigh};
12036   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12037                                    makeArrayRef(&CstHighArray[0], NumElts));
12038
12039   // Create the right shift.
12040   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12041   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12042                              CstShift, CstShift, CstShift, CstShift};
12043   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12044                                     makeArrayRef(&CstShiftArray[0], NumElts));
12045   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12046
12047   SDValue Low, High;
12048   if (Subtarget.hasSSE41()) {
12049     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12050     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12051     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12052     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12053     // Low will be bitcasted right away, so do not bother bitcasting back to its
12054     // original type.
12055     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12056                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12057     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12058     //                                 (uint4) 0x53000000, 0xaa);
12059     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12060     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12061     // High will be bitcasted right away, so do not bother bitcasting back to
12062     // its original type.
12063     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12064                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12065   } else {
12066     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12067     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12068                                      CstMask, CstMask, CstMask);
12069     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12070     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12071     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12072
12073     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12074     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12075   }
12076
12077   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12078   SDValue CstFAdd = DAG.getConstantFP(
12079       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12080   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12081                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12082   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12083                                    makeArrayRef(&CstFAddArray[0], NumElts));
12084
12085   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12086   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12087   SDValue FHigh =
12088       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12089   //     return (float4) lo + fhi;
12090   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12091   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12092 }
12093
12094 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12095                                                SelectionDAG &DAG) const {
12096   SDValue N0 = Op.getOperand(0);
12097   MVT SVT = N0.getSimpleValueType();
12098   SDLoc dl(Op);
12099
12100   switch (SVT.SimpleTy) {
12101   default:
12102     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12103   case MVT::v4i8:
12104   case MVT::v4i16:
12105   case MVT::v8i8:
12106   case MVT::v8i16: {
12107     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12108     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12109                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12110   }
12111   case MVT::v4i32:
12112   case MVT::v8i32:
12113     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12114   case MVT::v16i8:
12115   case MVT::v16i16:
12116     if (Subtarget->hasAVX512())
12117       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12118                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12119   }
12120   llvm_unreachable(nullptr);
12121 }
12122
12123 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12124                                            SelectionDAG &DAG) const {
12125   SDValue N0 = Op.getOperand(0);
12126   SDLoc dl(Op);
12127
12128   if (Op.getValueType().isVector())
12129     return lowerUINT_TO_FP_vec(Op, DAG);
12130
12131   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12132   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12133   // the optimization here.
12134   if (DAG.SignBitIsZero(N0))
12135     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12136
12137   MVT SrcVT = N0.getSimpleValueType();
12138   MVT DstVT = Op.getSimpleValueType();
12139   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12140     return LowerUINT_TO_FP_i64(Op, DAG);
12141   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12142     return LowerUINT_TO_FP_i32(Op, DAG);
12143   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12144     return SDValue();
12145
12146   // Make a 64-bit buffer, and use it to build an FILD.
12147   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12148   if (SrcVT == MVT::i32) {
12149     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
12150     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
12151                                      getPointerTy(), StackSlot, WordOff);
12152     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12153                                   StackSlot, MachinePointerInfo(),
12154                                   false, false, 0);
12155     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12156                                   OffsetSlot, MachinePointerInfo(),
12157                                   false, false, 0);
12158     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12159     return Fild;
12160   }
12161
12162   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12163   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12164                                StackSlot, MachinePointerInfo(),
12165                                false, false, 0);
12166   // For i64 source, we need to add the appropriate power of 2 if the input
12167   // was negative.  This is the same as the optimization in
12168   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12169   // we must be careful to do the computation in x87 extended precision, not
12170   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12171   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12172   MachineMemOperand *MMO =
12173     DAG.getMachineFunction()
12174     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12175                           MachineMemOperand::MOLoad, 8, 8);
12176
12177   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12178   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12179   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12180                                          MVT::i64, MMO);
12181
12182   APInt FF(32, 0x5F800000ULL);
12183
12184   // Check whether the sign bit is set.
12185   SDValue SignSet = DAG.getSetCC(dl,
12186                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
12187                                  Op.getOperand(0),
12188                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12189
12190   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12191   SDValue FudgePtr = DAG.getConstantPool(
12192                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
12193                                          getPointerTy());
12194
12195   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12196   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12197   SDValue Four = DAG.getIntPtrConstant(4, dl);
12198   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12199                                Zero, Four);
12200   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
12201
12202   // Load the value out, extending it from f32 to f80.
12203   // FIXME: Avoid the extend by constructing the right constant pool?
12204   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12205                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12206                                  MVT::f32, false, false, false, 4);
12207   // Extend everything to 80 bits to force it to be done on x87.
12208   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12209   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12210                      DAG.getIntPtrConstant(0, dl));
12211 }
12212
12213 std::pair<SDValue,SDValue>
12214 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12215                                     bool IsSigned, bool IsReplace) const {
12216   SDLoc DL(Op);
12217
12218   EVT DstTy = Op.getValueType();
12219
12220   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12221     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12222     DstTy = MVT::i64;
12223   }
12224
12225   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12226          DstTy.getSimpleVT() >= MVT::i16 &&
12227          "Unknown FP_TO_INT to lower!");
12228
12229   // These are really Legal.
12230   if (DstTy == MVT::i32 &&
12231       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12232     return std::make_pair(SDValue(), SDValue());
12233   if (Subtarget->is64Bit() &&
12234       DstTy == MVT::i64 &&
12235       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12236     return std::make_pair(SDValue(), SDValue());
12237
12238   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12239   // stack slot, or into the FTOL runtime function.
12240   MachineFunction &MF = DAG.getMachineFunction();
12241   unsigned MemSize = DstTy.getSizeInBits()/8;
12242   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12243   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12244
12245   unsigned Opc;
12246   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12247     Opc = X86ISD::WIN_FTOL;
12248   else
12249     switch (DstTy.getSimpleVT().SimpleTy) {
12250     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12251     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12252     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12253     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12254     }
12255
12256   SDValue Chain = DAG.getEntryNode();
12257   SDValue Value = Op.getOperand(0);
12258   EVT TheVT = Op.getOperand(0).getValueType();
12259   // FIXME This causes a redundant load/store if the SSE-class value is already
12260   // in memory, such as if it is on the callstack.
12261   if (isScalarFPTypeInSSEReg(TheVT)) {
12262     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12263     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12264                          MachinePointerInfo::getFixedStack(SSFI),
12265                          false, false, 0);
12266     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12267     SDValue Ops[] = {
12268       Chain, StackSlot, DAG.getValueType(TheVT)
12269     };
12270
12271     MachineMemOperand *MMO =
12272       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12273                               MachineMemOperand::MOLoad, MemSize, MemSize);
12274     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12275     Chain = Value.getValue(1);
12276     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12277     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12278   }
12279
12280   MachineMemOperand *MMO =
12281     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12282                             MachineMemOperand::MOStore, MemSize, MemSize);
12283
12284   if (Opc != X86ISD::WIN_FTOL) {
12285     // Build the FP_TO_INT*_IN_MEM
12286     SDValue Ops[] = { Chain, Value, StackSlot };
12287     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12288                                            Ops, DstTy, MMO);
12289     return std::make_pair(FIST, StackSlot);
12290   } else {
12291     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12292       DAG.getVTList(MVT::Other, MVT::Glue),
12293       Chain, Value);
12294     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12295       MVT::i32, ftol.getValue(1));
12296     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12297       MVT::i32, eax.getValue(2));
12298     SDValue Ops[] = { eax, edx };
12299     SDValue pair = IsReplace
12300       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12301       : DAG.getMergeValues(Ops, DL);
12302     return std::make_pair(pair, SDValue());
12303   }
12304 }
12305
12306 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12307                               const X86Subtarget *Subtarget) {
12308   MVT VT = Op->getSimpleValueType(0);
12309   SDValue In = Op->getOperand(0);
12310   MVT InVT = In.getSimpleValueType();
12311   SDLoc dl(Op);
12312
12313   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12314     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12315
12316   // Optimize vectors in AVX mode:
12317   //
12318   //   v8i16 -> v8i32
12319   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12320   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12321   //   Concat upper and lower parts.
12322   //
12323   //   v4i32 -> v4i64
12324   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12325   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12326   //   Concat upper and lower parts.
12327   //
12328
12329   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12330       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12331       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12332     return SDValue();
12333
12334   if (Subtarget->hasInt256())
12335     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12336
12337   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12338   SDValue Undef = DAG.getUNDEF(InVT);
12339   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12340   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12341   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12342
12343   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12344                              VT.getVectorNumElements()/2);
12345
12346   OpLo = DAG.getBitcast(HVT, OpLo);
12347   OpHi = DAG.getBitcast(HVT, OpHi);
12348
12349   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12350 }
12351
12352 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12353                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12354   MVT VT = Op->getSimpleValueType(0);
12355   SDValue In = Op->getOperand(0);
12356   MVT InVT = In.getSimpleValueType();
12357   SDLoc DL(Op);
12358   unsigned int NumElts = VT.getVectorNumElements();
12359   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12360     return SDValue();
12361
12362   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12363     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12364
12365   assert(InVT.getVectorElementType() == MVT::i1);
12366   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12367   SDValue One =
12368    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12369   SDValue Zero =
12370    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12371
12372   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12373   if (VT.is512BitVector())
12374     return V;
12375   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12376 }
12377
12378 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12379                                SelectionDAG &DAG) {
12380   if (Subtarget->hasFp256())
12381     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12382       return Res;
12383
12384   return SDValue();
12385 }
12386
12387 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12388                                 SelectionDAG &DAG) {
12389   SDLoc DL(Op);
12390   MVT VT = Op.getSimpleValueType();
12391   SDValue In = Op.getOperand(0);
12392   MVT SVT = In.getSimpleValueType();
12393
12394   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12395     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12396
12397   if (Subtarget->hasFp256())
12398     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12399       return Res;
12400
12401   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12402          VT.getVectorNumElements() != SVT.getVectorNumElements());
12403   return SDValue();
12404 }
12405
12406 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12407   SDLoc DL(Op);
12408   MVT VT = Op.getSimpleValueType();
12409   SDValue In = Op.getOperand(0);
12410   MVT InVT = In.getSimpleValueType();
12411
12412   if (VT == MVT::i1) {
12413     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12414            "Invalid scalar TRUNCATE operation");
12415     if (InVT.getSizeInBits() >= 32)
12416       return SDValue();
12417     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12418     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12419   }
12420   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12421          "Invalid TRUNCATE operation");
12422
12423   // move vector to mask - truncate solution for SKX
12424   if (VT.getVectorElementType() == MVT::i1) {
12425     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12426         Subtarget->hasBWI())
12427       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12428     if ((InVT.is256BitVector() || InVT.is128BitVector())
12429         && InVT.getScalarSizeInBits() <= 16 &&
12430         Subtarget->hasBWI() && Subtarget->hasVLX())
12431       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12432     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12433         Subtarget->hasDQI())
12434       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12435     if ((InVT.is256BitVector() || InVT.is128BitVector())
12436         && InVT.getScalarSizeInBits() >= 32 &&
12437         Subtarget->hasDQI() && Subtarget->hasVLX())
12438       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12439   }
12440   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12441     if (VT.getVectorElementType().getSizeInBits() >=8)
12442       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12443
12444     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12445     unsigned NumElts = InVT.getVectorNumElements();
12446     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12447     if (InVT.getSizeInBits() < 512) {
12448       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12449       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12450       InVT = ExtVT;
12451     }
12452
12453     SDValue OneV =
12454      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12455     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12456     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12457   }
12458
12459   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12460     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12461     if (Subtarget->hasInt256()) {
12462       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12463       In = DAG.getBitcast(MVT::v8i32, In);
12464       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12465                                 ShufMask);
12466       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12467                          DAG.getIntPtrConstant(0, DL));
12468     }
12469
12470     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12471                                DAG.getIntPtrConstant(0, DL));
12472     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12473                                DAG.getIntPtrConstant(2, DL));
12474     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12475     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12476     static const int ShufMask[] = {0, 2, 4, 6};
12477     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12478   }
12479
12480   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12481     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12482     if (Subtarget->hasInt256()) {
12483       In = DAG.getBitcast(MVT::v32i8, In);
12484
12485       SmallVector<SDValue,32> pshufbMask;
12486       for (unsigned i = 0; i < 2; ++i) {
12487         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12488         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12489         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12490         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12491         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12492         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12493         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12494         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12495         for (unsigned j = 0; j < 8; ++j)
12496           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12497       }
12498       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12499       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12500       In = DAG.getBitcast(MVT::v4i64, In);
12501
12502       static const int ShufMask[] = {0,  2,  -1,  -1};
12503       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12504                                 &ShufMask[0]);
12505       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12506                        DAG.getIntPtrConstant(0, DL));
12507       return DAG.getBitcast(VT, In);
12508     }
12509
12510     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12511                                DAG.getIntPtrConstant(0, DL));
12512
12513     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12514                                DAG.getIntPtrConstant(4, DL));
12515
12516     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12517     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12518
12519     // The PSHUFB mask:
12520     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12521                                    -1, -1, -1, -1, -1, -1, -1, -1};
12522
12523     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12524     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12525     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12526
12527     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12528     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12529
12530     // The MOVLHPS Mask:
12531     static const int ShufMask2[] = {0, 1, 4, 5};
12532     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12533     return DAG.getBitcast(MVT::v8i16, res);
12534   }
12535
12536   // Handle truncation of V256 to V128 using shuffles.
12537   if (!VT.is128BitVector() || !InVT.is256BitVector())
12538     return SDValue();
12539
12540   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12541
12542   unsigned NumElems = VT.getVectorNumElements();
12543   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12544
12545   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12546   // Prepare truncation shuffle mask
12547   for (unsigned i = 0; i != NumElems; ++i)
12548     MaskVec[i] = i * 2;
12549   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12550                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12551   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12552                      DAG.getIntPtrConstant(0, DL));
12553 }
12554
12555 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12556                                            SelectionDAG &DAG) const {
12557   assert(!Op.getSimpleValueType().isVector());
12558
12559   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12560     /*IsSigned=*/ true, /*IsReplace=*/ false);
12561   SDValue FIST = Vals.first, StackSlot = Vals.second;
12562   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12563   if (!FIST.getNode()) return Op;
12564
12565   if (StackSlot.getNode())
12566     // Load the result.
12567     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12568                        FIST, StackSlot, MachinePointerInfo(),
12569                        false, false, false, 0);
12570
12571   // The node is the result.
12572   return FIST;
12573 }
12574
12575 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12576                                            SelectionDAG &DAG) const {
12577   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12578     /*IsSigned=*/ false, /*IsReplace=*/ false);
12579   SDValue FIST = Vals.first, StackSlot = Vals.second;
12580   assert(FIST.getNode() && "Unexpected failure");
12581
12582   if (StackSlot.getNode())
12583     // Load the result.
12584     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12585                        FIST, StackSlot, MachinePointerInfo(),
12586                        false, false, false, 0);
12587
12588   // The node is the result.
12589   return FIST;
12590 }
12591
12592 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12593   SDLoc DL(Op);
12594   MVT VT = Op.getSimpleValueType();
12595   SDValue In = Op.getOperand(0);
12596   MVT SVT = In.getSimpleValueType();
12597
12598   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12599
12600   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12601                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12602                                  In, DAG.getUNDEF(SVT)));
12603 }
12604
12605 /// The only differences between FABS and FNEG are the mask and the logic op.
12606 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12607 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12608   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12609          "Wrong opcode for lowering FABS or FNEG.");
12610
12611   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12612
12613   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12614   // into an FNABS. We'll lower the FABS after that if it is still in use.
12615   if (IsFABS)
12616     for (SDNode *User : Op->uses())
12617       if (User->getOpcode() == ISD::FNEG)
12618         return Op;
12619
12620   SDValue Op0 = Op.getOperand(0);
12621   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12622
12623   SDLoc dl(Op);
12624   MVT VT = Op.getSimpleValueType();
12625   // Assume scalar op for initialization; update for vector if needed.
12626   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12627   // generate a 16-byte vector constant and logic op even for the scalar case.
12628   // Using a 16-byte mask allows folding the load of the mask with
12629   // the logic op, so it can save (~4 bytes) on code size.
12630   MVT EltVT = VT;
12631   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12632   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12633   // decide if we should generate a 16-byte constant mask when we only need 4 or
12634   // 8 bytes for the scalar case.
12635   if (VT.isVector()) {
12636     EltVT = VT.getVectorElementType();
12637     NumElts = VT.getVectorNumElements();
12638   }
12639
12640   unsigned EltBits = EltVT.getSizeInBits();
12641   LLVMContext *Context = DAG.getContext();
12642   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12643   APInt MaskElt =
12644     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12645   Constant *C = ConstantInt::get(*Context, MaskElt);
12646   C = ConstantVector::getSplat(NumElts, C);
12647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12648   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12649   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12650   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12651                              MachinePointerInfo::getConstantPool(),
12652                              false, false, false, Alignment);
12653
12654   if (VT.isVector()) {
12655     // For a vector, cast operands to a vector type, perform the logic op,
12656     // and cast the result back to the original value type.
12657     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12658     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12659     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12660                               : DAG.getBitcast(VecVT, Op0);
12661     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12662     return DAG.getBitcast(VT,
12663                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12664   }
12665
12666   // If not vector, then scalar.
12667   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12668   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12669   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12670 }
12671
12672 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12674   LLVMContext *Context = DAG.getContext();
12675   SDValue Op0 = Op.getOperand(0);
12676   SDValue Op1 = Op.getOperand(1);
12677   SDLoc dl(Op);
12678   MVT VT = Op.getSimpleValueType();
12679   MVT SrcVT = Op1.getSimpleValueType();
12680
12681   // If second operand is smaller, extend it first.
12682   if (SrcVT.bitsLT(VT)) {
12683     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12684     SrcVT = VT;
12685   }
12686   // And if it is bigger, shrink it first.
12687   if (SrcVT.bitsGT(VT)) {
12688     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12689     SrcVT = VT;
12690   }
12691
12692   // At this point the operands and the result should have the same
12693   // type, and that won't be f80 since that is not custom lowered.
12694
12695   const fltSemantics &Sem =
12696       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12697   const unsigned SizeInBits = VT.getSizeInBits();
12698
12699   SmallVector<Constant *, 4> CV(
12700       VT == MVT::f64 ? 2 : 4,
12701       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12702
12703   // First, clear all bits but the sign bit from the second operand (sign).
12704   CV[0] = ConstantFP::get(*Context,
12705                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12706   Constant *C = ConstantVector::get(CV);
12707   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12708   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12709                               MachinePointerInfo::getConstantPool(),
12710                               false, false, false, 16);
12711   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12712
12713   // Next, clear the sign bit from the first operand (magnitude).
12714   // If it's a constant, we can clear it here.
12715   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12716     APFloat APF = Op0CN->getValueAPF();
12717     // If the magnitude is a positive zero, the sign bit alone is enough.
12718     if (APF.isPosZero())
12719       return SignBit;
12720     APF.clearSign();
12721     CV[0] = ConstantFP::get(*Context, APF);
12722   } else {
12723     CV[0] = ConstantFP::get(
12724         *Context,
12725         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12726   }
12727   C = ConstantVector::get(CV);
12728   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12729   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12730                             MachinePointerInfo::getConstantPool(),
12731                             false, false, false, 16);
12732   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12733   if (!isa<ConstantFPSDNode>(Op0))
12734     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12735
12736   // OR the magnitude value with the sign bit.
12737   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12738 }
12739
12740 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12741   SDValue N0 = Op.getOperand(0);
12742   SDLoc dl(Op);
12743   MVT VT = Op.getSimpleValueType();
12744
12745   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12746   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12747                                   DAG.getConstant(1, dl, VT));
12748   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12749 }
12750
12751 // Check whether an OR'd tree is PTEST-able.
12752 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12753                                       SelectionDAG &DAG) {
12754   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12755
12756   if (!Subtarget->hasSSE41())
12757     return SDValue();
12758
12759   if (!Op->hasOneUse())
12760     return SDValue();
12761
12762   SDNode *N = Op.getNode();
12763   SDLoc DL(N);
12764
12765   SmallVector<SDValue, 8> Opnds;
12766   DenseMap<SDValue, unsigned> VecInMap;
12767   SmallVector<SDValue, 8> VecIns;
12768   EVT VT = MVT::Other;
12769
12770   // Recognize a special case where a vector is casted into wide integer to
12771   // test all 0s.
12772   Opnds.push_back(N->getOperand(0));
12773   Opnds.push_back(N->getOperand(1));
12774
12775   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12776     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12777     // BFS traverse all OR'd operands.
12778     if (I->getOpcode() == ISD::OR) {
12779       Opnds.push_back(I->getOperand(0));
12780       Opnds.push_back(I->getOperand(1));
12781       // Re-evaluate the number of nodes to be traversed.
12782       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12783       continue;
12784     }
12785
12786     // Quit if a non-EXTRACT_VECTOR_ELT
12787     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12788       return SDValue();
12789
12790     // Quit if without a constant index.
12791     SDValue Idx = I->getOperand(1);
12792     if (!isa<ConstantSDNode>(Idx))
12793       return SDValue();
12794
12795     SDValue ExtractedFromVec = I->getOperand(0);
12796     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12797     if (M == VecInMap.end()) {
12798       VT = ExtractedFromVec.getValueType();
12799       // Quit if not 128/256-bit vector.
12800       if (!VT.is128BitVector() && !VT.is256BitVector())
12801         return SDValue();
12802       // Quit if not the same type.
12803       if (VecInMap.begin() != VecInMap.end() &&
12804           VT != VecInMap.begin()->first.getValueType())
12805         return SDValue();
12806       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12807       VecIns.push_back(ExtractedFromVec);
12808     }
12809     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12810   }
12811
12812   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12813          "Not extracted from 128-/256-bit vector.");
12814
12815   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12816
12817   for (DenseMap<SDValue, unsigned>::const_iterator
12818         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12819     // Quit if not all elements are used.
12820     if (I->second != FullMask)
12821       return SDValue();
12822   }
12823
12824   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12825
12826   // Cast all vectors into TestVT for PTEST.
12827   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12828     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12829
12830   // If more than one full vectors are evaluated, OR them first before PTEST.
12831   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12832     // Each iteration will OR 2 nodes and append the result until there is only
12833     // 1 node left, i.e. the final OR'd value of all vectors.
12834     SDValue LHS = VecIns[Slot];
12835     SDValue RHS = VecIns[Slot + 1];
12836     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12837   }
12838
12839   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12840                      VecIns.back(), VecIns.back());
12841 }
12842
12843 /// \brief return true if \c Op has a use that doesn't just read flags.
12844 static bool hasNonFlagsUse(SDValue Op) {
12845   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12846        ++UI) {
12847     SDNode *User = *UI;
12848     unsigned UOpNo = UI.getOperandNo();
12849     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12850       // Look pass truncate.
12851       UOpNo = User->use_begin().getOperandNo();
12852       User = *User->use_begin();
12853     }
12854
12855     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12856         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12857       return true;
12858   }
12859   return false;
12860 }
12861
12862 /// Emit nodes that will be selected as "test Op0,Op0", or something
12863 /// equivalent.
12864 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12865                                     SelectionDAG &DAG) const {
12866   if (Op.getValueType() == MVT::i1) {
12867     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12868     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12869                        DAG.getConstant(0, dl, MVT::i8));
12870   }
12871   // CF and OF aren't always set the way we want. Determine which
12872   // of these we need.
12873   bool NeedCF = false;
12874   bool NeedOF = false;
12875   switch (X86CC) {
12876   default: break;
12877   case X86::COND_A: case X86::COND_AE:
12878   case X86::COND_B: case X86::COND_BE:
12879     NeedCF = true;
12880     break;
12881   case X86::COND_G: case X86::COND_GE:
12882   case X86::COND_L: case X86::COND_LE:
12883   case X86::COND_O: case X86::COND_NO: {
12884     // Check if we really need to set the
12885     // Overflow flag. If NoSignedWrap is present
12886     // that is not actually needed.
12887     switch (Op->getOpcode()) {
12888     case ISD::ADD:
12889     case ISD::SUB:
12890     case ISD::MUL:
12891     case ISD::SHL: {
12892       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12893       if (BinNode->Flags.hasNoSignedWrap())
12894         break;
12895     }
12896     default:
12897       NeedOF = true;
12898       break;
12899     }
12900     break;
12901   }
12902   }
12903   // See if we can use the EFLAGS value from the operand instead of
12904   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12905   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12906   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12907     // Emit a CMP with 0, which is the TEST pattern.
12908     //if (Op.getValueType() == MVT::i1)
12909     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12910     //                     DAG.getConstant(0, MVT::i1));
12911     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12912                        DAG.getConstant(0, dl, Op.getValueType()));
12913   }
12914   unsigned Opcode = 0;
12915   unsigned NumOperands = 0;
12916
12917   // Truncate operations may prevent the merge of the SETCC instruction
12918   // and the arithmetic instruction before it. Attempt to truncate the operands
12919   // of the arithmetic instruction and use a reduced bit-width instruction.
12920   bool NeedTruncation = false;
12921   SDValue ArithOp = Op;
12922   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12923     SDValue Arith = Op->getOperand(0);
12924     // Both the trunc and the arithmetic op need to have one user each.
12925     if (Arith->hasOneUse())
12926       switch (Arith.getOpcode()) {
12927         default: break;
12928         case ISD::ADD:
12929         case ISD::SUB:
12930         case ISD::AND:
12931         case ISD::OR:
12932         case ISD::XOR: {
12933           NeedTruncation = true;
12934           ArithOp = Arith;
12935         }
12936       }
12937   }
12938
12939   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12940   // which may be the result of a CAST.  We use the variable 'Op', which is the
12941   // non-casted variable when we check for possible users.
12942   switch (ArithOp.getOpcode()) {
12943   case ISD::ADD:
12944     // Due to an isel shortcoming, be conservative if this add is likely to be
12945     // selected as part of a load-modify-store instruction. When the root node
12946     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12947     // uses of other nodes in the match, such as the ADD in this case. This
12948     // leads to the ADD being left around and reselected, with the result being
12949     // two adds in the output.  Alas, even if none our users are stores, that
12950     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12951     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12952     // climbing the DAG back to the root, and it doesn't seem to be worth the
12953     // effort.
12954     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12955          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12956       if (UI->getOpcode() != ISD::CopyToReg &&
12957           UI->getOpcode() != ISD::SETCC &&
12958           UI->getOpcode() != ISD::STORE)
12959         goto default_case;
12960
12961     if (ConstantSDNode *C =
12962         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12963       // An add of one will be selected as an INC.
12964       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12965         Opcode = X86ISD::INC;
12966         NumOperands = 1;
12967         break;
12968       }
12969
12970       // An add of negative one (subtract of one) will be selected as a DEC.
12971       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12972         Opcode = X86ISD::DEC;
12973         NumOperands = 1;
12974         break;
12975       }
12976     }
12977
12978     // Otherwise use a regular EFLAGS-setting add.
12979     Opcode = X86ISD::ADD;
12980     NumOperands = 2;
12981     break;
12982   case ISD::SHL:
12983   case ISD::SRL:
12984     // If we have a constant logical shift that's only used in a comparison
12985     // against zero turn it into an equivalent AND. This allows turning it into
12986     // a TEST instruction later.
12987     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12988         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12989       EVT VT = Op.getValueType();
12990       unsigned BitWidth = VT.getSizeInBits();
12991       unsigned ShAmt = Op->getConstantOperandVal(1);
12992       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12993         break;
12994       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12995                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12996                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12997       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12998         break;
12999       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13000                                 DAG.getConstant(Mask, dl, VT));
13001       DAG.ReplaceAllUsesWith(Op, New);
13002       Op = New;
13003     }
13004     break;
13005
13006   case ISD::AND:
13007     // If the primary and result isn't used, don't bother using X86ISD::AND,
13008     // because a TEST instruction will be better.
13009     if (!hasNonFlagsUse(Op))
13010       break;
13011     // FALL THROUGH
13012   case ISD::SUB:
13013   case ISD::OR:
13014   case ISD::XOR:
13015     // Due to the ISEL shortcoming noted above, be conservative if this op is
13016     // likely to be selected as part of a load-modify-store instruction.
13017     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13018            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13019       if (UI->getOpcode() == ISD::STORE)
13020         goto default_case;
13021
13022     // Otherwise use a regular EFLAGS-setting instruction.
13023     switch (ArithOp.getOpcode()) {
13024     default: llvm_unreachable("unexpected operator!");
13025     case ISD::SUB: Opcode = X86ISD::SUB; break;
13026     case ISD::XOR: Opcode = X86ISD::XOR; break;
13027     case ISD::AND: Opcode = X86ISD::AND; break;
13028     case ISD::OR: {
13029       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13030         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13031         if (EFLAGS.getNode())
13032           return EFLAGS;
13033       }
13034       Opcode = X86ISD::OR;
13035       break;
13036     }
13037     }
13038
13039     NumOperands = 2;
13040     break;
13041   case X86ISD::ADD:
13042   case X86ISD::SUB:
13043   case X86ISD::INC:
13044   case X86ISD::DEC:
13045   case X86ISD::OR:
13046   case X86ISD::XOR:
13047   case X86ISD::AND:
13048     return SDValue(Op.getNode(), 1);
13049   default:
13050   default_case:
13051     break;
13052   }
13053
13054   // If we found that truncation is beneficial, perform the truncation and
13055   // update 'Op'.
13056   if (NeedTruncation) {
13057     EVT VT = Op.getValueType();
13058     SDValue WideVal = Op->getOperand(0);
13059     EVT WideVT = WideVal.getValueType();
13060     unsigned ConvertedOp = 0;
13061     // Use a target machine opcode to prevent further DAGCombine
13062     // optimizations that may separate the arithmetic operations
13063     // from the setcc node.
13064     switch (WideVal.getOpcode()) {
13065       default: break;
13066       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13067       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13068       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13069       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13070       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13071     }
13072
13073     if (ConvertedOp) {
13074       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13075       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13076         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13077         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13078         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13079       }
13080     }
13081   }
13082
13083   if (Opcode == 0)
13084     // Emit a CMP with 0, which is the TEST pattern.
13085     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13086                        DAG.getConstant(0, dl, Op.getValueType()));
13087
13088   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13089   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13090
13091   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13092   DAG.ReplaceAllUsesWith(Op, New);
13093   return SDValue(New.getNode(), 1);
13094 }
13095
13096 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13097 /// equivalent.
13098 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13099                                    SDLoc dl, SelectionDAG &DAG) const {
13100   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13101     if (C->getAPIntValue() == 0)
13102       return EmitTest(Op0, X86CC, dl, DAG);
13103
13104      if (Op0.getValueType() == MVT::i1)
13105        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13106   }
13107
13108   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13109        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13110     // Do the comparison at i32 if it's smaller, besides the Atom case.
13111     // This avoids subregister aliasing issues. Keep the smaller reference
13112     // if we're optimizing for size, however, as that'll allow better folding
13113     // of memory operations.
13114     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13115         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13116             Attribute::MinSize) &&
13117         !Subtarget->isAtom()) {
13118       unsigned ExtendOp =
13119           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13120       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13121       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13122     }
13123     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13124     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13125     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13126                               Op0, Op1);
13127     return SDValue(Sub.getNode(), 1);
13128   }
13129   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13130 }
13131
13132 /// Convert a comparison if required by the subtarget.
13133 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13134                                                  SelectionDAG &DAG) const {
13135   // If the subtarget does not support the FUCOMI instruction, floating-point
13136   // comparisons have to be converted.
13137   if (Subtarget->hasCMov() ||
13138       Cmp.getOpcode() != X86ISD::CMP ||
13139       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13140       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13141     return Cmp;
13142
13143   // The instruction selector will select an FUCOM instruction instead of
13144   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13145   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13146   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13147   SDLoc dl(Cmp);
13148   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13149   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13150   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13151                             DAG.getConstant(8, dl, MVT::i8));
13152   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13153   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13154 }
13155
13156 /// The minimum architected relative accuracy is 2^-12. We need one
13157 /// Newton-Raphson step to have a good float result (24 bits of precision).
13158 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13159                                             DAGCombinerInfo &DCI,
13160                                             unsigned &RefinementSteps,
13161                                             bool &UseOneConstNR) const {
13162   EVT VT = Op.getValueType();
13163   const char *RecipOp;
13164
13165   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13166   // TODO: Add support for AVX512 (v16f32).
13167   // It is likely not profitable to do this for f64 because a double-precision
13168   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13169   // instructions: convert to single, rsqrtss, convert back to double, refine
13170   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13171   // along with FMA, this could be a throughput win.
13172   if (VT == MVT::f32 && Subtarget->hasSSE1())
13173     RecipOp = "sqrtf";
13174   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13175            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13176     RecipOp = "vec-sqrtf";
13177   else
13178     return SDValue();
13179
13180   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13181   if (!Recips.isEnabled(RecipOp))
13182     return SDValue();
13183
13184   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13185   UseOneConstNR = false;
13186   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13187 }
13188
13189 /// The minimum architected relative accuracy is 2^-12. We need one
13190 /// Newton-Raphson step to have a good float result (24 bits of precision).
13191 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13192                                             DAGCombinerInfo &DCI,
13193                                             unsigned &RefinementSteps) const {
13194   EVT VT = Op.getValueType();
13195   const char *RecipOp;
13196
13197   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13198   // TODO: Add support for AVX512 (v16f32).
13199   // It is likely not profitable to do this for f64 because a double-precision
13200   // reciprocal estimate with refinement on x86 prior to FMA requires
13201   // 15 instructions: convert to single, rcpss, convert back to double, refine
13202   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13203   // along with FMA, this could be a throughput win.
13204   if (VT == MVT::f32 && Subtarget->hasSSE1())
13205     RecipOp = "divf";
13206   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13207            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13208     RecipOp = "vec-divf";
13209   else
13210     return SDValue();
13211
13212   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13213   if (!Recips.isEnabled(RecipOp))
13214     return SDValue();
13215
13216   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13217   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13218 }
13219
13220 /// If we have at least two divisions that use the same divisor, convert to
13221 /// multplication by a reciprocal. This may need to be adjusted for a given
13222 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13223 /// This is because we still need one division to calculate the reciprocal and
13224 /// then we need two multiplies by that reciprocal as replacements for the
13225 /// original divisions.
13226 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13227   return NumUsers > 1;
13228 }
13229
13230 static bool isAllOnes(SDValue V) {
13231   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13232   return C && C->isAllOnesValue();
13233 }
13234
13235 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13236 /// if it's possible.
13237 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13238                                      SDLoc dl, SelectionDAG &DAG) const {
13239   SDValue Op0 = And.getOperand(0);
13240   SDValue Op1 = And.getOperand(1);
13241   if (Op0.getOpcode() == ISD::TRUNCATE)
13242     Op0 = Op0.getOperand(0);
13243   if (Op1.getOpcode() == ISD::TRUNCATE)
13244     Op1 = Op1.getOperand(0);
13245
13246   SDValue LHS, RHS;
13247   if (Op1.getOpcode() == ISD::SHL)
13248     std::swap(Op0, Op1);
13249   if (Op0.getOpcode() == ISD::SHL) {
13250     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13251       if (And00C->getZExtValue() == 1) {
13252         // If we looked past a truncate, check that it's only truncating away
13253         // known zeros.
13254         unsigned BitWidth = Op0.getValueSizeInBits();
13255         unsigned AndBitWidth = And.getValueSizeInBits();
13256         if (BitWidth > AndBitWidth) {
13257           APInt Zeros, Ones;
13258           DAG.computeKnownBits(Op0, Zeros, Ones);
13259           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13260             return SDValue();
13261         }
13262         LHS = Op1;
13263         RHS = Op0.getOperand(1);
13264       }
13265   } else if (Op1.getOpcode() == ISD::Constant) {
13266     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13267     uint64_t AndRHSVal = AndRHS->getZExtValue();
13268     SDValue AndLHS = Op0;
13269
13270     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13271       LHS = AndLHS.getOperand(0);
13272       RHS = AndLHS.getOperand(1);
13273     }
13274
13275     // Use BT if the immediate can't be encoded in a TEST instruction.
13276     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13277       LHS = AndLHS;
13278       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13279     }
13280   }
13281
13282   if (LHS.getNode()) {
13283     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13284     // instruction.  Since the shift amount is in-range-or-undefined, we know
13285     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13286     // the encoding for the i16 version is larger than the i32 version.
13287     // Also promote i16 to i32 for performance / code size reason.
13288     if (LHS.getValueType() == MVT::i8 ||
13289         LHS.getValueType() == MVT::i16)
13290       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13291
13292     // If the operand types disagree, extend the shift amount to match.  Since
13293     // BT ignores high bits (like shifts) we can use anyextend.
13294     if (LHS.getValueType() != RHS.getValueType())
13295       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13296
13297     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13298     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13299     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13300                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13301   }
13302
13303   return SDValue();
13304 }
13305
13306 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13307 /// mask CMPs.
13308 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13309                               SDValue &Op1) {
13310   unsigned SSECC;
13311   bool Swap = false;
13312
13313   // SSE Condition code mapping:
13314   //  0 - EQ
13315   //  1 - LT
13316   //  2 - LE
13317   //  3 - UNORD
13318   //  4 - NEQ
13319   //  5 - NLT
13320   //  6 - NLE
13321   //  7 - ORD
13322   switch (SetCCOpcode) {
13323   default: llvm_unreachable("Unexpected SETCC condition");
13324   case ISD::SETOEQ:
13325   case ISD::SETEQ:  SSECC = 0; break;
13326   case ISD::SETOGT:
13327   case ISD::SETGT:  Swap = true; // Fallthrough
13328   case ISD::SETLT:
13329   case ISD::SETOLT: SSECC = 1; break;
13330   case ISD::SETOGE:
13331   case ISD::SETGE:  Swap = true; // Fallthrough
13332   case ISD::SETLE:
13333   case ISD::SETOLE: SSECC = 2; break;
13334   case ISD::SETUO:  SSECC = 3; break;
13335   case ISD::SETUNE:
13336   case ISD::SETNE:  SSECC = 4; break;
13337   case ISD::SETULE: Swap = true; // Fallthrough
13338   case ISD::SETUGE: SSECC = 5; break;
13339   case ISD::SETULT: Swap = true; // Fallthrough
13340   case ISD::SETUGT: SSECC = 6; break;
13341   case ISD::SETO:   SSECC = 7; break;
13342   case ISD::SETUEQ:
13343   case ISD::SETONE: SSECC = 8; break;
13344   }
13345   if (Swap)
13346     std::swap(Op0, Op1);
13347
13348   return SSECC;
13349 }
13350
13351 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13352 // ones, and then concatenate the result back.
13353 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13354   MVT VT = Op.getSimpleValueType();
13355
13356   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13357          "Unsupported value type for operation");
13358
13359   unsigned NumElems = VT.getVectorNumElements();
13360   SDLoc dl(Op);
13361   SDValue CC = Op.getOperand(2);
13362
13363   // Extract the LHS vectors
13364   SDValue LHS = Op.getOperand(0);
13365   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13366   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13367
13368   // Extract the RHS vectors
13369   SDValue RHS = Op.getOperand(1);
13370   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13371   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13372
13373   // Issue the operation on the smaller types and concatenate the result back
13374   MVT EltVT = VT.getVectorElementType();
13375   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13376   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13377                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13378                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13379 }
13380
13381 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13382   SDValue Op0 = Op.getOperand(0);
13383   SDValue Op1 = Op.getOperand(1);
13384   SDValue CC = Op.getOperand(2);
13385   MVT VT = Op.getSimpleValueType();
13386   SDLoc dl(Op);
13387
13388   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13389          "Unexpected type for boolean compare operation");
13390   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13391   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13392                                DAG.getConstant(-1, dl, VT));
13393   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13394                                DAG.getConstant(-1, dl, VT));
13395   switch (SetCCOpcode) {
13396   default: llvm_unreachable("Unexpected SETCC condition");
13397   case ISD::SETEQ:
13398     // (x == y) -> ~(x ^ y)
13399     return DAG.getNode(ISD::XOR, dl, VT,
13400                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13401                        DAG.getConstant(-1, dl, VT));
13402   case ISD::SETNE:
13403     // (x != y) -> (x ^ y)
13404     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13405   case ISD::SETUGT:
13406   case ISD::SETGT:
13407     // (x > y) -> (x & ~y)
13408     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13409   case ISD::SETULT:
13410   case ISD::SETLT:
13411     // (x < y) -> (~x & y)
13412     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13413   case ISD::SETULE:
13414   case ISD::SETLE:
13415     // (x <= y) -> (~x | y)
13416     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13417   case ISD::SETUGE:
13418   case ISD::SETGE:
13419     // (x >=y) -> (x | ~y)
13420     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13421   }
13422 }
13423
13424 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13425                                      const X86Subtarget *Subtarget) {
13426   SDValue Op0 = Op.getOperand(0);
13427   SDValue Op1 = Op.getOperand(1);
13428   SDValue CC = Op.getOperand(2);
13429   MVT VT = Op.getSimpleValueType();
13430   SDLoc dl(Op);
13431
13432   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13433          Op.getValueType().getScalarType() == MVT::i1 &&
13434          "Cannot set masked compare for this operation");
13435
13436   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13437   unsigned  Opc = 0;
13438   bool Unsigned = false;
13439   bool Swap = false;
13440   unsigned SSECC;
13441   switch (SetCCOpcode) {
13442   default: llvm_unreachable("Unexpected SETCC condition");
13443   case ISD::SETNE:  SSECC = 4; break;
13444   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13445   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13446   case ISD::SETLT:  Swap = true; //fall-through
13447   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13448   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13449   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13450   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13451   case ISD::SETULE: Unsigned = true; //fall-through
13452   case ISD::SETLE:  SSECC = 2; break;
13453   }
13454
13455   if (Swap)
13456     std::swap(Op0, Op1);
13457   if (Opc)
13458     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13459   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13460   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13461                      DAG.getConstant(SSECC, dl, MVT::i8));
13462 }
13463
13464 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13465 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13466 /// return an empty value.
13467 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13468 {
13469   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13470   if (!BV)
13471     return SDValue();
13472
13473   MVT VT = Op1.getSimpleValueType();
13474   MVT EVT = VT.getVectorElementType();
13475   unsigned n = VT.getVectorNumElements();
13476   SmallVector<SDValue, 8> ULTOp1;
13477
13478   for (unsigned i = 0; i < n; ++i) {
13479     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13480     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13481       return SDValue();
13482
13483     // Avoid underflow.
13484     APInt Val = Elt->getAPIntValue();
13485     if (Val == 0)
13486       return SDValue();
13487
13488     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13489   }
13490
13491   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13492 }
13493
13494 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13495                            SelectionDAG &DAG) {
13496   SDValue Op0 = Op.getOperand(0);
13497   SDValue Op1 = Op.getOperand(1);
13498   SDValue CC = Op.getOperand(2);
13499   MVT VT = Op.getSimpleValueType();
13500   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13501   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13502   SDLoc dl(Op);
13503
13504   if (isFP) {
13505 #ifndef NDEBUG
13506     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13507     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13508 #endif
13509
13510     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13511     unsigned Opc = X86ISD::CMPP;
13512     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13513       assert(VT.getVectorNumElements() <= 16);
13514       Opc = X86ISD::CMPM;
13515     }
13516     // In the two special cases we can't handle, emit two comparisons.
13517     if (SSECC == 8) {
13518       unsigned CC0, CC1;
13519       unsigned CombineOpc;
13520       if (SetCCOpcode == ISD::SETUEQ) {
13521         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13522       } else {
13523         assert(SetCCOpcode == ISD::SETONE);
13524         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13525       }
13526
13527       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13528                                  DAG.getConstant(CC0, dl, MVT::i8));
13529       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13530                                  DAG.getConstant(CC1, dl, MVT::i8));
13531       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13532     }
13533     // Handle all other FP comparisons here.
13534     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13535                        DAG.getConstant(SSECC, dl, MVT::i8));
13536   }
13537
13538   // Break 256-bit integer vector compare into smaller ones.
13539   if (VT.is256BitVector() && !Subtarget->hasInt256())
13540     return Lower256IntVSETCC(Op, DAG);
13541
13542   EVT OpVT = Op1.getValueType();
13543   if (OpVT.getVectorElementType() == MVT::i1)
13544     return LowerBoolVSETCC_AVX512(Op, DAG);
13545
13546   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13547   if (Subtarget->hasAVX512()) {
13548     if (Op1.getValueType().is512BitVector() ||
13549         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13550         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13551       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13552
13553     // In AVX-512 architecture setcc returns mask with i1 elements,
13554     // But there is no compare instruction for i8 and i16 elements in KNL.
13555     // We are not talking about 512-bit operands in this case, these
13556     // types are illegal.
13557     if (MaskResult &&
13558         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13559          OpVT.getVectorElementType().getSizeInBits() >= 8))
13560       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13561                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13562   }
13563
13564   // We are handling one of the integer comparisons here.  Since SSE only has
13565   // GT and EQ comparisons for integer, swapping operands and multiple
13566   // operations may be required for some comparisons.
13567   unsigned Opc;
13568   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13569   bool Subus = false;
13570
13571   switch (SetCCOpcode) {
13572   default: llvm_unreachable("Unexpected SETCC condition");
13573   case ISD::SETNE:  Invert = true;
13574   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13575   case ISD::SETLT:  Swap = true;
13576   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13577   case ISD::SETGE:  Swap = true;
13578   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13579                     Invert = true; break;
13580   case ISD::SETULT: Swap = true;
13581   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13582                     FlipSigns = true; break;
13583   case ISD::SETUGE: Swap = true;
13584   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13585                     FlipSigns = true; Invert = true; break;
13586   }
13587
13588   // Special case: Use min/max operations for SETULE/SETUGE
13589   MVT VET = VT.getVectorElementType();
13590   bool hasMinMax =
13591        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13592     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13593
13594   if (hasMinMax) {
13595     switch (SetCCOpcode) {
13596     default: break;
13597     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13598     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13599     }
13600
13601     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13602   }
13603
13604   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13605   if (!MinMax && hasSubus) {
13606     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13607     // Op0 u<= Op1:
13608     //   t = psubus Op0, Op1
13609     //   pcmpeq t, <0..0>
13610     switch (SetCCOpcode) {
13611     default: break;
13612     case ISD::SETULT: {
13613       // If the comparison is against a constant we can turn this into a
13614       // setule.  With psubus, setule does not require a swap.  This is
13615       // beneficial because the constant in the register is no longer
13616       // destructed as the destination so it can be hoisted out of a loop.
13617       // Only do this pre-AVX since vpcmp* is no longer destructive.
13618       if (Subtarget->hasAVX())
13619         break;
13620       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13621       if (ULEOp1.getNode()) {
13622         Op1 = ULEOp1;
13623         Subus = true; Invert = false; Swap = false;
13624       }
13625       break;
13626     }
13627     // Psubus is better than flip-sign because it requires no inversion.
13628     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13629     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13630     }
13631
13632     if (Subus) {
13633       Opc = X86ISD::SUBUS;
13634       FlipSigns = false;
13635     }
13636   }
13637
13638   if (Swap)
13639     std::swap(Op0, Op1);
13640
13641   // Check that the operation in question is available (most are plain SSE2,
13642   // but PCMPGTQ and PCMPEQQ have different requirements).
13643   if (VT == MVT::v2i64) {
13644     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13645       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13646
13647       // First cast everything to the right type.
13648       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13649       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13650
13651       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13652       // bits of the inputs before performing those operations. The lower
13653       // compare is always unsigned.
13654       SDValue SB;
13655       if (FlipSigns) {
13656         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13657       } else {
13658         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13659         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13660         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13661                          Sign, Zero, Sign, Zero);
13662       }
13663       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13664       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13665
13666       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13667       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13668       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13669
13670       // Create masks for only the low parts/high parts of the 64 bit integers.
13671       static const int MaskHi[] = { 1, 1, 3, 3 };
13672       static const int MaskLo[] = { 0, 0, 2, 2 };
13673       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13674       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13675       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13676
13677       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13678       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13679
13680       if (Invert)
13681         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13682
13683       return DAG.getBitcast(VT, Result);
13684     }
13685
13686     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13687       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13688       // pcmpeqd + pshufd + pand.
13689       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13690
13691       // First cast everything to the right type.
13692       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13693       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13694
13695       // Do the compare.
13696       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13697
13698       // Make sure the lower and upper halves are both all-ones.
13699       static const int Mask[] = { 1, 0, 3, 2 };
13700       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13701       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13702
13703       if (Invert)
13704         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13705
13706       return DAG.getBitcast(VT, Result);
13707     }
13708   }
13709
13710   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13711   // bits of the inputs before performing those operations.
13712   if (FlipSigns) {
13713     EVT EltVT = VT.getVectorElementType();
13714     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13715                                  VT);
13716     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13717     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13718   }
13719
13720   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13721
13722   // If the logical-not of the result is required, perform that now.
13723   if (Invert)
13724     Result = DAG.getNOT(dl, Result, VT);
13725
13726   if (MinMax)
13727     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13728
13729   if (Subus)
13730     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13731                          getZeroVector(VT, Subtarget, DAG, dl));
13732
13733   return Result;
13734 }
13735
13736 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13737
13738   MVT VT = Op.getSimpleValueType();
13739
13740   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13741
13742   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13743          && "SetCC type must be 8-bit or 1-bit integer");
13744   SDValue Op0 = Op.getOperand(0);
13745   SDValue Op1 = Op.getOperand(1);
13746   SDLoc dl(Op);
13747   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13748
13749   // Optimize to BT if possible.
13750   // Lower (X & (1 << N)) == 0 to BT(X, N).
13751   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13752   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13753   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13754       Op1.getOpcode() == ISD::Constant &&
13755       cast<ConstantSDNode>(Op1)->isNullValue() &&
13756       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13757     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13758     if (NewSetCC.getNode()) {
13759       if (VT == MVT::i1)
13760         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13761       return NewSetCC;
13762     }
13763   }
13764
13765   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13766   // these.
13767   if (Op1.getOpcode() == ISD::Constant &&
13768       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13769        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13770       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13771
13772     // If the input is a setcc, then reuse the input setcc or use a new one with
13773     // the inverted condition.
13774     if (Op0.getOpcode() == X86ISD::SETCC) {
13775       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13776       bool Invert = (CC == ISD::SETNE) ^
13777         cast<ConstantSDNode>(Op1)->isNullValue();
13778       if (!Invert)
13779         return Op0;
13780
13781       CCode = X86::GetOppositeBranchCondition(CCode);
13782       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13783                                   DAG.getConstant(CCode, dl, MVT::i8),
13784                                   Op0.getOperand(1));
13785       if (VT == MVT::i1)
13786         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13787       return SetCC;
13788     }
13789   }
13790   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13791       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13792       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13793
13794     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13795     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13796   }
13797
13798   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13799   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13800   if (X86CC == X86::COND_INVALID)
13801     return SDValue();
13802
13803   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13804   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13805   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13806                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13807   if (VT == MVT::i1)
13808     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13809   return SetCC;
13810 }
13811
13812 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13813 static bool isX86LogicalCmp(SDValue Op) {
13814   unsigned Opc = Op.getNode()->getOpcode();
13815   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13816       Opc == X86ISD::SAHF)
13817     return true;
13818   if (Op.getResNo() == 1 &&
13819       (Opc == X86ISD::ADD ||
13820        Opc == X86ISD::SUB ||
13821        Opc == X86ISD::ADC ||
13822        Opc == X86ISD::SBB ||
13823        Opc == X86ISD::SMUL ||
13824        Opc == X86ISD::UMUL ||
13825        Opc == X86ISD::INC ||
13826        Opc == X86ISD::DEC ||
13827        Opc == X86ISD::OR ||
13828        Opc == X86ISD::XOR ||
13829        Opc == X86ISD::AND))
13830     return true;
13831
13832   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13833     return true;
13834
13835   return false;
13836 }
13837
13838 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13839   if (V.getOpcode() != ISD::TRUNCATE)
13840     return false;
13841
13842   SDValue VOp0 = V.getOperand(0);
13843   unsigned InBits = VOp0.getValueSizeInBits();
13844   unsigned Bits = V.getValueSizeInBits();
13845   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13846 }
13847
13848 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13849   bool addTest = true;
13850   SDValue Cond  = Op.getOperand(0);
13851   SDValue Op1 = Op.getOperand(1);
13852   SDValue Op2 = Op.getOperand(2);
13853   SDLoc DL(Op);
13854   EVT VT = Op1.getValueType();
13855   SDValue CC;
13856
13857   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13858   // are available or VBLENDV if AVX is available.
13859   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13860   if (Cond.getOpcode() == ISD::SETCC &&
13861       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13862        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13863       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13864     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13865     int SSECC = translateX86FSETCC(
13866         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13867
13868     if (SSECC != 8) {
13869       if (Subtarget->hasAVX512()) {
13870         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13871                                   DAG.getConstant(SSECC, DL, MVT::i8));
13872         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13873       }
13874
13875       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13876                                 DAG.getConstant(SSECC, DL, MVT::i8));
13877
13878       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13879       // of 3 logic instructions for size savings and potentially speed.
13880       // Unfortunately, there is no scalar form of VBLENDV.
13881
13882       // If either operand is a constant, don't try this. We can expect to
13883       // optimize away at least one of the logic instructions later in that
13884       // case, so that sequence would be faster than a variable blend.
13885
13886       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13887       // uses XMM0 as the selection register. That may need just as many
13888       // instructions as the AND/ANDN/OR sequence due to register moves, so
13889       // don't bother.
13890
13891       if (Subtarget->hasAVX() &&
13892           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13893
13894         // Convert to vectors, do a VSELECT, and convert back to scalar.
13895         // All of the conversions should be optimized away.
13896
13897         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13898         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13899         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13900         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13901
13902         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13903         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13904
13905         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13906
13907         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13908                            VSel, DAG.getIntPtrConstant(0, DL));
13909       }
13910       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13911       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13912       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13913     }
13914   }
13915
13916     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13917       SDValue Op1Scalar;
13918       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13919         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13920       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13921         Op1Scalar = Op1.getOperand(0);
13922       SDValue Op2Scalar;
13923       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13924         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13925       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13926         Op2Scalar = Op2.getOperand(0);
13927       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13928         SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13929                                         Op1Scalar.getValueType(),
13930                                         Cond, Op1Scalar, Op2Scalar);
13931         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13932           return DAG.getBitcast(VT, newSelect);
13933         SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13934         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13935                            DAG.getIntPtrConstant(0, DL));
13936     }
13937   }
13938
13939   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13940     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13941     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13942                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13943     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13944                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13945     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13946                                     Cond, Op1, Op2);
13947     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13948   }
13949
13950   if (Cond.getOpcode() == ISD::SETCC) {
13951     SDValue NewCond = LowerSETCC(Cond, DAG);
13952     if (NewCond.getNode())
13953       Cond = NewCond;
13954   }
13955
13956   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13957   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13958   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13959   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13960   if (Cond.getOpcode() == X86ISD::SETCC &&
13961       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13962       isZero(Cond.getOperand(1).getOperand(1))) {
13963     SDValue Cmp = Cond.getOperand(1);
13964
13965     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13966
13967     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13968         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13969       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13970
13971       SDValue CmpOp0 = Cmp.getOperand(0);
13972       // Apply further optimizations for special cases
13973       // (select (x != 0), -1, 0) -> neg & sbb
13974       // (select (x == 0), 0, -1) -> neg & sbb
13975       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13976         if (YC->isNullValue() &&
13977             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13978           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13979           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13980                                     DAG.getConstant(0, DL,
13981                                                     CmpOp0.getValueType()),
13982                                     CmpOp0);
13983           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13984                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13985                                     SDValue(Neg.getNode(), 1));
13986           return Res;
13987         }
13988
13989       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13990                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13991       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13992
13993       SDValue Res =   // Res = 0 or -1.
13994         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13995                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13996
13997       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13998         Res = DAG.getNOT(DL, Res, Res.getValueType());
13999
14000       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14001       if (!N2C || !N2C->isNullValue())
14002         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14003       return Res;
14004     }
14005   }
14006
14007   // Look past (and (setcc_carry (cmp ...)), 1).
14008   if (Cond.getOpcode() == ISD::AND &&
14009       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14010     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14011     if (C && C->getAPIntValue() == 1)
14012       Cond = Cond.getOperand(0);
14013   }
14014
14015   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14016   // setting operand in place of the X86ISD::SETCC.
14017   unsigned CondOpcode = Cond.getOpcode();
14018   if (CondOpcode == X86ISD::SETCC ||
14019       CondOpcode == X86ISD::SETCC_CARRY) {
14020     CC = Cond.getOperand(0);
14021
14022     SDValue Cmp = Cond.getOperand(1);
14023     unsigned Opc = Cmp.getOpcode();
14024     MVT VT = Op.getSimpleValueType();
14025
14026     bool IllegalFPCMov = false;
14027     if (VT.isFloatingPoint() && !VT.isVector() &&
14028         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14029       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14030
14031     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14032         Opc == X86ISD::BT) { // FIXME
14033       Cond = Cmp;
14034       addTest = false;
14035     }
14036   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14037              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14038              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14039               Cond.getOperand(0).getValueType() != MVT::i8)) {
14040     SDValue LHS = Cond.getOperand(0);
14041     SDValue RHS = Cond.getOperand(1);
14042     unsigned X86Opcode;
14043     unsigned X86Cond;
14044     SDVTList VTs;
14045     switch (CondOpcode) {
14046     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14047     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14048     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14049     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14050     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14051     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14052     default: llvm_unreachable("unexpected overflowing operator");
14053     }
14054     if (CondOpcode == ISD::UMULO)
14055       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14056                           MVT::i32);
14057     else
14058       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14059
14060     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14061
14062     if (CondOpcode == ISD::UMULO)
14063       Cond = X86Op.getValue(2);
14064     else
14065       Cond = X86Op.getValue(1);
14066
14067     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14068     addTest = false;
14069   }
14070
14071   if (addTest) {
14072     // Look pass the truncate if the high bits are known zero.
14073     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14074         Cond = Cond.getOperand(0);
14075
14076     // We know the result of AND is compared against zero. Try to match
14077     // it to BT.
14078     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14079       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14080       if (NewSetCC.getNode()) {
14081         CC = NewSetCC.getOperand(0);
14082         Cond = NewSetCC.getOperand(1);
14083         addTest = false;
14084       }
14085     }
14086   }
14087
14088   if (addTest) {
14089     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14090     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14091   }
14092
14093   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14094   // a <  b ?  0 : -1 -> RES = setcc_carry
14095   // a >= b ? -1 :  0 -> RES = setcc_carry
14096   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14097   if (Cond.getOpcode() == X86ISD::SUB) {
14098     Cond = ConvertCmpIfNecessary(Cond, DAG);
14099     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14100
14101     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14102         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14103       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14104                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14105                                 Cond);
14106       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14107         return DAG.getNOT(DL, Res, Res.getValueType());
14108       return Res;
14109     }
14110   }
14111
14112   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14113   // widen the cmov and push the truncate through. This avoids introducing a new
14114   // branch during isel and doesn't add any extensions.
14115   if (Op.getValueType() == MVT::i8 &&
14116       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14117     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14118     if (T1.getValueType() == T2.getValueType() &&
14119         // Blacklist CopyFromReg to avoid partial register stalls.
14120         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14121       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14122       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14123       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14124     }
14125   }
14126
14127   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14128   // condition is true.
14129   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14130   SDValue Ops[] = { Op2, Op1, CC, Cond };
14131   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14132 }
14133
14134 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14135                                        const X86Subtarget *Subtarget,
14136                                        SelectionDAG &DAG) {
14137   MVT VT = Op->getSimpleValueType(0);
14138   SDValue In = Op->getOperand(0);
14139   MVT InVT = In.getSimpleValueType();
14140   MVT VTElt = VT.getVectorElementType();
14141   MVT InVTElt = InVT.getVectorElementType();
14142   SDLoc dl(Op);
14143
14144   // SKX processor
14145   if ((InVTElt == MVT::i1) &&
14146       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14147         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14148
14149        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14150         VTElt.getSizeInBits() <= 16)) ||
14151
14152        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14153         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14154
14155        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14156         VTElt.getSizeInBits() >= 32))))
14157     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14158
14159   unsigned int NumElts = VT.getVectorNumElements();
14160
14161   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14162     return SDValue();
14163
14164   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14165     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14166       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14167     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14168   }
14169
14170   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14171   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14172   SDValue NegOne =
14173    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14174                    ExtVT);
14175   SDValue Zero =
14176    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14177
14178   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14179   if (VT.is512BitVector())
14180     return V;
14181   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14182 }
14183
14184 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14185                                              const X86Subtarget *Subtarget,
14186                                              SelectionDAG &DAG) {
14187   SDValue In = Op->getOperand(0);
14188   MVT VT = Op->getSimpleValueType(0);
14189   MVT InVT = In.getSimpleValueType();
14190   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14191
14192   MVT InSVT = InVT.getScalarType();
14193   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14194
14195   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14196     return SDValue();
14197   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14198     return SDValue();
14199
14200   SDLoc dl(Op);
14201
14202   // SSE41 targets can use the pmovsx* instructions directly.
14203   if (Subtarget->hasSSE41())
14204     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14205
14206   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14207   SDValue Curr = In;
14208   MVT CurrVT = InVT;
14209
14210   // As SRAI is only available on i16/i32 types, we expand only up to i32
14211   // and handle i64 separately.
14212   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14213     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14214     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14215     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14216     Curr = DAG.getBitcast(CurrVT, Curr);
14217   }
14218
14219   SDValue SignExt = Curr;
14220   if (CurrVT != InVT) {
14221     unsigned SignExtShift =
14222         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14223     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14224                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14225   }
14226
14227   if (CurrVT == VT)
14228     return SignExt;
14229
14230   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14231     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14232                                DAG.getConstant(31, dl, MVT::i8));
14233     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14234     return DAG.getBitcast(VT, Ext);
14235   }
14236
14237   return SDValue();
14238 }
14239
14240 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14241                                 SelectionDAG &DAG) {
14242   MVT VT = Op->getSimpleValueType(0);
14243   SDValue In = Op->getOperand(0);
14244   MVT InVT = In.getSimpleValueType();
14245   SDLoc dl(Op);
14246
14247   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14248     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14249
14250   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14251       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14252       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14253     return SDValue();
14254
14255   if (Subtarget->hasInt256())
14256     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14257
14258   // Optimize vectors in AVX mode
14259   // Sign extend  v8i16 to v8i32 and
14260   //              v4i32 to v4i64
14261   //
14262   // Divide input vector into two parts
14263   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14264   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14265   // concat the vectors to original VT
14266
14267   unsigned NumElems = InVT.getVectorNumElements();
14268   SDValue Undef = DAG.getUNDEF(InVT);
14269
14270   SmallVector<int,8> ShufMask1(NumElems, -1);
14271   for (unsigned i = 0; i != NumElems/2; ++i)
14272     ShufMask1[i] = i;
14273
14274   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14275
14276   SmallVector<int,8> ShufMask2(NumElems, -1);
14277   for (unsigned i = 0; i != NumElems/2; ++i)
14278     ShufMask2[i] = i + NumElems/2;
14279
14280   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14281
14282   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14283                                 VT.getVectorNumElements()/2);
14284
14285   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14286   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14287
14288   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14289 }
14290
14291 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14292 // may emit an illegal shuffle but the expansion is still better than scalar
14293 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14294 // we'll emit a shuffle and a arithmetic shift.
14295 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14296 // TODO: It is possible to support ZExt by zeroing the undef values during
14297 // the shuffle phase or after the shuffle.
14298 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14299                                  SelectionDAG &DAG) {
14300   MVT RegVT = Op.getSimpleValueType();
14301   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14302   assert(RegVT.isInteger() &&
14303          "We only custom lower integer vector sext loads.");
14304
14305   // Nothing useful we can do without SSE2 shuffles.
14306   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14307
14308   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14309   SDLoc dl(Ld);
14310   EVT MemVT = Ld->getMemoryVT();
14311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14312   unsigned RegSz = RegVT.getSizeInBits();
14313
14314   ISD::LoadExtType Ext = Ld->getExtensionType();
14315
14316   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14317          && "Only anyext and sext are currently implemented.");
14318   assert(MemVT != RegVT && "Cannot extend to the same type");
14319   assert(MemVT.isVector() && "Must load a vector from memory");
14320
14321   unsigned NumElems = RegVT.getVectorNumElements();
14322   unsigned MemSz = MemVT.getSizeInBits();
14323   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14324
14325   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14326     // The only way in which we have a legal 256-bit vector result but not the
14327     // integer 256-bit operations needed to directly lower a sextload is if we
14328     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14329     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14330     // correctly legalized. We do this late to allow the canonical form of
14331     // sextload to persist throughout the rest of the DAG combiner -- it wants
14332     // to fold together any extensions it can, and so will fuse a sign_extend
14333     // of an sextload into a sextload targeting a wider value.
14334     SDValue Load;
14335     if (MemSz == 128) {
14336       // Just switch this to a normal load.
14337       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14338                                        "it must be a legal 128-bit vector "
14339                                        "type!");
14340       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14341                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14342                   Ld->isInvariant(), Ld->getAlignment());
14343     } else {
14344       assert(MemSz < 128 &&
14345              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14346       // Do an sext load to a 128-bit vector type. We want to use the same
14347       // number of elements, but elements half as wide. This will end up being
14348       // recursively lowered by this routine, but will succeed as we definitely
14349       // have all the necessary features if we're using AVX1.
14350       EVT HalfEltVT =
14351           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14352       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14353       Load =
14354           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14355                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14356                          Ld->isNonTemporal(), Ld->isInvariant(),
14357                          Ld->getAlignment());
14358     }
14359
14360     // Replace chain users with the new chain.
14361     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14362     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14363
14364     // Finally, do a normal sign-extend to the desired register.
14365     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14366   }
14367
14368   // All sizes must be a power of two.
14369   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14370          "Non-power-of-two elements are not custom lowered!");
14371
14372   // Attempt to load the original value using scalar loads.
14373   // Find the largest scalar type that divides the total loaded size.
14374   MVT SclrLoadTy = MVT::i8;
14375   for (MVT Tp : MVT::integer_valuetypes()) {
14376     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14377       SclrLoadTy = Tp;
14378     }
14379   }
14380
14381   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14382   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14383       (64 <= MemSz))
14384     SclrLoadTy = MVT::f64;
14385
14386   // Calculate the number of scalar loads that we need to perform
14387   // in order to load our vector from memory.
14388   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14389
14390   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14391          "Can only lower sext loads with a single scalar load!");
14392
14393   unsigned loadRegZize = RegSz;
14394   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14395     loadRegZize = 128;
14396
14397   // Represent our vector as a sequence of elements which are the
14398   // largest scalar that we can load.
14399   EVT LoadUnitVecVT = EVT::getVectorVT(
14400       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14401
14402   // Represent the data using the same element type that is stored in
14403   // memory. In practice, we ''widen'' MemVT.
14404   EVT WideVecVT =
14405       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14406                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14407
14408   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14409          "Invalid vector type");
14410
14411   // We can't shuffle using an illegal type.
14412   assert(TLI.isTypeLegal(WideVecVT) &&
14413          "We only lower types that form legal widened vector types");
14414
14415   SmallVector<SDValue, 8> Chains;
14416   SDValue Ptr = Ld->getBasePtr();
14417   SDValue Increment =
14418       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14419   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14420
14421   for (unsigned i = 0; i < NumLoads; ++i) {
14422     // Perform a single load.
14423     SDValue ScalarLoad =
14424         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14425                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14426                     Ld->getAlignment());
14427     Chains.push_back(ScalarLoad.getValue(1));
14428     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14429     // another round of DAGCombining.
14430     if (i == 0)
14431       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14432     else
14433       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14434                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14435
14436     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14437   }
14438
14439   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14440
14441   // Bitcast the loaded value to a vector of the original element type, in
14442   // the size of the target vector type.
14443   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14444   unsigned SizeRatio = RegSz / MemSz;
14445
14446   if (Ext == ISD::SEXTLOAD) {
14447     // If we have SSE4.1, we can directly emit a VSEXT node.
14448     if (Subtarget->hasSSE41()) {
14449       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14450       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14451       return Sext;
14452     }
14453
14454     // Otherwise we'll shuffle the small elements in the high bits of the
14455     // larger type and perform an arithmetic shift. If the shift is not legal
14456     // it's better to scalarize.
14457     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14458            "We can't implement a sext load without an arithmetic right shift!");
14459
14460     // Redistribute the loaded elements into the different locations.
14461     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14462     for (unsigned i = 0; i != NumElems; ++i)
14463       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14464
14465     SDValue Shuff = DAG.getVectorShuffle(
14466         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14467
14468     Shuff = DAG.getBitcast(RegVT, Shuff);
14469
14470     // Build the arithmetic shift.
14471     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14472                    MemVT.getVectorElementType().getSizeInBits();
14473     Shuff =
14474         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14475                     DAG.getConstant(Amt, dl, RegVT));
14476
14477     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14478     return Shuff;
14479   }
14480
14481   // Redistribute the loaded elements into the different locations.
14482   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14483   for (unsigned i = 0; i != NumElems; ++i)
14484     ShuffleVec[i * SizeRatio] = i;
14485
14486   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14487                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14488
14489   // Bitcast to the requested type.
14490   Shuff = DAG.getBitcast(RegVT, Shuff);
14491   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14492   return Shuff;
14493 }
14494
14495 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14496 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14497 // from the AND / OR.
14498 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14499   Opc = Op.getOpcode();
14500   if (Opc != ISD::OR && Opc != ISD::AND)
14501     return false;
14502   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14503           Op.getOperand(0).hasOneUse() &&
14504           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14505           Op.getOperand(1).hasOneUse());
14506 }
14507
14508 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14509 // 1 and that the SETCC node has a single use.
14510 static bool isXor1OfSetCC(SDValue Op) {
14511   if (Op.getOpcode() != ISD::XOR)
14512     return false;
14513   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14514   if (N1C && N1C->getAPIntValue() == 1) {
14515     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14516       Op.getOperand(0).hasOneUse();
14517   }
14518   return false;
14519 }
14520
14521 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14522   bool addTest = true;
14523   SDValue Chain = Op.getOperand(0);
14524   SDValue Cond  = Op.getOperand(1);
14525   SDValue Dest  = Op.getOperand(2);
14526   SDLoc dl(Op);
14527   SDValue CC;
14528   bool Inverted = false;
14529
14530   if (Cond.getOpcode() == ISD::SETCC) {
14531     // Check for setcc([su]{add,sub,mul}o == 0).
14532     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14533         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14534         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14535         Cond.getOperand(0).getResNo() == 1 &&
14536         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14537          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14538          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14539          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14540          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14541          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14542       Inverted = true;
14543       Cond = Cond.getOperand(0);
14544     } else {
14545       SDValue NewCond = LowerSETCC(Cond, DAG);
14546       if (NewCond.getNode())
14547         Cond = NewCond;
14548     }
14549   }
14550 #if 0
14551   // FIXME: LowerXALUO doesn't handle these!!
14552   else if (Cond.getOpcode() == X86ISD::ADD  ||
14553            Cond.getOpcode() == X86ISD::SUB  ||
14554            Cond.getOpcode() == X86ISD::SMUL ||
14555            Cond.getOpcode() == X86ISD::UMUL)
14556     Cond = LowerXALUO(Cond, DAG);
14557 #endif
14558
14559   // Look pass (and (setcc_carry (cmp ...)), 1).
14560   if (Cond.getOpcode() == ISD::AND &&
14561       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14562     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14563     if (C && C->getAPIntValue() == 1)
14564       Cond = Cond.getOperand(0);
14565   }
14566
14567   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14568   // setting operand in place of the X86ISD::SETCC.
14569   unsigned CondOpcode = Cond.getOpcode();
14570   if (CondOpcode == X86ISD::SETCC ||
14571       CondOpcode == X86ISD::SETCC_CARRY) {
14572     CC = Cond.getOperand(0);
14573
14574     SDValue Cmp = Cond.getOperand(1);
14575     unsigned Opc = Cmp.getOpcode();
14576     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14577     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14578       Cond = Cmp;
14579       addTest = false;
14580     } else {
14581       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14582       default: break;
14583       case X86::COND_O:
14584       case X86::COND_B:
14585         // These can only come from an arithmetic instruction with overflow,
14586         // e.g. SADDO, UADDO.
14587         Cond = Cond.getNode()->getOperand(1);
14588         addTest = false;
14589         break;
14590       }
14591     }
14592   }
14593   CondOpcode = Cond.getOpcode();
14594   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14595       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14596       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14597        Cond.getOperand(0).getValueType() != MVT::i8)) {
14598     SDValue LHS = Cond.getOperand(0);
14599     SDValue RHS = Cond.getOperand(1);
14600     unsigned X86Opcode;
14601     unsigned X86Cond;
14602     SDVTList VTs;
14603     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14604     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14605     // X86ISD::INC).
14606     switch (CondOpcode) {
14607     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14608     case ISD::SADDO:
14609       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14610         if (C->isOne()) {
14611           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14612           break;
14613         }
14614       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14615     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14616     case ISD::SSUBO:
14617       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14618         if (C->isOne()) {
14619           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14620           break;
14621         }
14622       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14623     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14624     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14625     default: llvm_unreachable("unexpected overflowing operator");
14626     }
14627     if (Inverted)
14628       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14629     if (CondOpcode == ISD::UMULO)
14630       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14631                           MVT::i32);
14632     else
14633       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14634
14635     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14636
14637     if (CondOpcode == ISD::UMULO)
14638       Cond = X86Op.getValue(2);
14639     else
14640       Cond = X86Op.getValue(1);
14641
14642     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14643     addTest = false;
14644   } else {
14645     unsigned CondOpc;
14646     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14647       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14648       if (CondOpc == ISD::OR) {
14649         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14650         // two branches instead of an explicit OR instruction with a
14651         // separate test.
14652         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14653             isX86LogicalCmp(Cmp)) {
14654           CC = Cond.getOperand(0).getOperand(0);
14655           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14656                               Chain, Dest, CC, Cmp);
14657           CC = Cond.getOperand(1).getOperand(0);
14658           Cond = Cmp;
14659           addTest = false;
14660         }
14661       } else { // ISD::AND
14662         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14663         // two branches instead of an explicit AND instruction with a
14664         // separate test. However, we only do this if this block doesn't
14665         // have a fall-through edge, because this requires an explicit
14666         // jmp when the condition is false.
14667         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14668             isX86LogicalCmp(Cmp) &&
14669             Op.getNode()->hasOneUse()) {
14670           X86::CondCode CCode =
14671             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14672           CCode = X86::GetOppositeBranchCondition(CCode);
14673           CC = DAG.getConstant(CCode, dl, MVT::i8);
14674           SDNode *User = *Op.getNode()->use_begin();
14675           // Look for an unconditional branch following this conditional branch.
14676           // We need this because we need to reverse the successors in order
14677           // to implement FCMP_OEQ.
14678           if (User->getOpcode() == ISD::BR) {
14679             SDValue FalseBB = User->getOperand(1);
14680             SDNode *NewBR =
14681               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14682             assert(NewBR == User);
14683             (void)NewBR;
14684             Dest = FalseBB;
14685
14686             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14687                                 Chain, Dest, CC, Cmp);
14688             X86::CondCode CCode =
14689               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14690             CCode = X86::GetOppositeBranchCondition(CCode);
14691             CC = DAG.getConstant(CCode, dl, MVT::i8);
14692             Cond = Cmp;
14693             addTest = false;
14694           }
14695         }
14696       }
14697     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14698       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14699       // It should be transformed during dag combiner except when the condition
14700       // is set by a arithmetics with overflow node.
14701       X86::CondCode CCode =
14702         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14703       CCode = X86::GetOppositeBranchCondition(CCode);
14704       CC = DAG.getConstant(CCode, dl, MVT::i8);
14705       Cond = Cond.getOperand(0).getOperand(1);
14706       addTest = false;
14707     } else if (Cond.getOpcode() == ISD::SETCC &&
14708                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14709       // For FCMP_OEQ, we can emit
14710       // two branches instead of an explicit AND instruction with a
14711       // separate test. However, we only do this if this block doesn't
14712       // have a fall-through edge, because this requires an explicit
14713       // jmp when the condition is false.
14714       if (Op.getNode()->hasOneUse()) {
14715         SDNode *User = *Op.getNode()->use_begin();
14716         // Look for an unconditional branch following this conditional branch.
14717         // We need this because we need to reverse the successors in order
14718         // to implement FCMP_OEQ.
14719         if (User->getOpcode() == ISD::BR) {
14720           SDValue FalseBB = User->getOperand(1);
14721           SDNode *NewBR =
14722             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14723           assert(NewBR == User);
14724           (void)NewBR;
14725           Dest = FalseBB;
14726
14727           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14728                                     Cond.getOperand(0), Cond.getOperand(1));
14729           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14730           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14731           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14732                               Chain, Dest, CC, Cmp);
14733           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14734           Cond = Cmp;
14735           addTest = false;
14736         }
14737       }
14738     } else if (Cond.getOpcode() == ISD::SETCC &&
14739                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14740       // For FCMP_UNE, we can emit
14741       // two branches instead of an explicit AND instruction with a
14742       // separate test. However, we only do this if this block doesn't
14743       // have a fall-through edge, because this requires an explicit
14744       // jmp when the condition is false.
14745       if (Op.getNode()->hasOneUse()) {
14746         SDNode *User = *Op.getNode()->use_begin();
14747         // Look for an unconditional branch following this conditional branch.
14748         // We need this because we need to reverse the successors in order
14749         // to implement FCMP_UNE.
14750         if (User->getOpcode() == ISD::BR) {
14751           SDValue FalseBB = User->getOperand(1);
14752           SDNode *NewBR =
14753             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14754           assert(NewBR == User);
14755           (void)NewBR;
14756
14757           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14758                                     Cond.getOperand(0), Cond.getOperand(1));
14759           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14760           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14761           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14762                               Chain, Dest, CC, Cmp);
14763           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14764           Cond = Cmp;
14765           addTest = false;
14766           Dest = FalseBB;
14767         }
14768       }
14769     }
14770   }
14771
14772   if (addTest) {
14773     // Look pass the truncate if the high bits are known zero.
14774     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14775         Cond = Cond.getOperand(0);
14776
14777     // We know the result of AND is compared against zero. Try to match
14778     // it to BT.
14779     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14780       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14781       if (NewSetCC.getNode()) {
14782         CC = NewSetCC.getOperand(0);
14783         Cond = NewSetCC.getOperand(1);
14784         addTest = false;
14785       }
14786     }
14787   }
14788
14789   if (addTest) {
14790     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14791     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14792     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14793   }
14794   Cond = ConvertCmpIfNecessary(Cond, DAG);
14795   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14796                      Chain, Dest, CC, Cond);
14797 }
14798
14799 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14800 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14801 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14802 // that the guard pages used by the OS virtual memory manager are allocated in
14803 // correct sequence.
14804 SDValue
14805 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14806                                            SelectionDAG &DAG) const {
14807   MachineFunction &MF = DAG.getMachineFunction();
14808   bool SplitStack = MF.shouldSplitStack();
14809   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14810                SplitStack;
14811   SDLoc dl(Op);
14812
14813   if (!Lower) {
14814     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14815     SDNode* Node = Op.getNode();
14816
14817     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14818     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14819         " not tell us which reg is the stack pointer!");
14820     EVT VT = Node->getValueType(0);
14821     SDValue Tmp1 = SDValue(Node, 0);
14822     SDValue Tmp2 = SDValue(Node, 1);
14823     SDValue Tmp3 = Node->getOperand(2);
14824     SDValue Chain = Tmp1.getOperand(0);
14825
14826     // Chain the dynamic stack allocation so that it doesn't modify the stack
14827     // pointer when other instructions are using the stack.
14828     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14829         SDLoc(Node));
14830
14831     SDValue Size = Tmp2.getOperand(1);
14832     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14833     Chain = SP.getValue(1);
14834     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14835     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14836     unsigned StackAlign = TFI.getStackAlignment();
14837     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14838     if (Align > StackAlign)
14839       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14840           DAG.getConstant(-(uint64_t)Align, dl, VT));
14841     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14842
14843     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14844         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14845         SDLoc(Node));
14846
14847     SDValue Ops[2] = { Tmp1, Tmp2 };
14848     return DAG.getMergeValues(Ops, dl);
14849   }
14850
14851   // Get the inputs.
14852   SDValue Chain = Op.getOperand(0);
14853   SDValue Size  = Op.getOperand(1);
14854   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14855   EVT VT = Op.getNode()->getValueType(0);
14856
14857   bool Is64Bit = Subtarget->is64Bit();
14858   EVT SPTy = getPointerTy();
14859
14860   if (SplitStack) {
14861     MachineRegisterInfo &MRI = MF.getRegInfo();
14862
14863     if (Is64Bit) {
14864       // The 64 bit implementation of segmented stacks needs to clobber both r10
14865       // r11. This makes it impossible to use it along with nested parameters.
14866       const Function *F = MF.getFunction();
14867
14868       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14869            I != E; ++I)
14870         if (I->hasNestAttr())
14871           report_fatal_error("Cannot use segmented stacks with functions that "
14872                              "have nested arguments.");
14873     }
14874
14875     const TargetRegisterClass *AddrRegClass =
14876       getRegClassFor(getPointerTy());
14877     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14878     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14879     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14880                                 DAG.getRegister(Vreg, SPTy));
14881     SDValue Ops1[2] = { Value, Chain };
14882     return DAG.getMergeValues(Ops1, dl);
14883   } else {
14884     SDValue Flag;
14885     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14886
14887     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14888     Flag = Chain.getValue(1);
14889     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14890
14891     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14892
14893     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14894     unsigned SPReg = RegInfo->getStackRegister();
14895     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14896     Chain = SP.getValue(1);
14897
14898     if (Align) {
14899       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14900                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14901       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14902     }
14903
14904     SDValue Ops1[2] = { SP, Chain };
14905     return DAG.getMergeValues(Ops1, dl);
14906   }
14907 }
14908
14909 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14910   MachineFunction &MF = DAG.getMachineFunction();
14911   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14912
14913   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14914   SDLoc DL(Op);
14915
14916   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14917     // vastart just stores the address of the VarArgsFrameIndex slot into the
14918     // memory location argument.
14919     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14920                                    getPointerTy());
14921     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14922                         MachinePointerInfo(SV), false, false, 0);
14923   }
14924
14925   // __va_list_tag:
14926   //   gp_offset         (0 - 6 * 8)
14927   //   fp_offset         (48 - 48 + 8 * 16)
14928   //   overflow_arg_area (point to parameters coming in memory).
14929   //   reg_save_area
14930   SmallVector<SDValue, 8> MemOps;
14931   SDValue FIN = Op.getOperand(1);
14932   // Store gp_offset
14933   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14934                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14935                                                DL, MVT::i32),
14936                                FIN, MachinePointerInfo(SV), false, false, 0);
14937   MemOps.push_back(Store);
14938
14939   // Store fp_offset
14940   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14941                     FIN, DAG.getIntPtrConstant(4, DL));
14942   Store = DAG.getStore(Op.getOperand(0), DL,
14943                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14944                                        MVT::i32),
14945                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14946   MemOps.push_back(Store);
14947
14948   // Store ptr to overflow_arg_area
14949   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14950                     FIN, DAG.getIntPtrConstant(4, DL));
14951   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14952                                     getPointerTy());
14953   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14954                        MachinePointerInfo(SV, 8),
14955                        false, false, 0);
14956   MemOps.push_back(Store);
14957
14958   // Store ptr to reg_save_area.
14959   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14960                     FIN, DAG.getIntPtrConstant(8, DL));
14961   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14962                                     getPointerTy());
14963   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14964                        MachinePointerInfo(SV, 16), false, false, 0);
14965   MemOps.push_back(Store);
14966   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14967 }
14968
14969 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14970   assert(Subtarget->is64Bit() &&
14971          "LowerVAARG only handles 64-bit va_arg!");
14972   assert((Subtarget->isTargetLinux() ||
14973           Subtarget->isTargetDarwin()) &&
14974           "Unhandled target in LowerVAARG");
14975   assert(Op.getNode()->getNumOperands() == 4);
14976   SDValue Chain = Op.getOperand(0);
14977   SDValue SrcPtr = Op.getOperand(1);
14978   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14979   unsigned Align = Op.getConstantOperandVal(3);
14980   SDLoc dl(Op);
14981
14982   EVT ArgVT = Op.getNode()->getValueType(0);
14983   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14984   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14985   uint8_t ArgMode;
14986
14987   // Decide which area this value should be read from.
14988   // TODO: Implement the AMD64 ABI in its entirety. This simple
14989   // selection mechanism works only for the basic types.
14990   if (ArgVT == MVT::f80) {
14991     llvm_unreachable("va_arg for f80 not yet implemented");
14992   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14993     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14994   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14995     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14996   } else {
14997     llvm_unreachable("Unhandled argument type in LowerVAARG");
14998   }
14999
15000   if (ArgMode == 2) {
15001     // Sanity Check: Make sure using fp_offset makes sense.
15002     assert(!Subtarget->useSoftFloat() &&
15003            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15004                Attribute::NoImplicitFloat)) &&
15005            Subtarget->hasSSE1());
15006   }
15007
15008   // Insert VAARG_64 node into the DAG
15009   // VAARG_64 returns two values: Variable Argument Address, Chain
15010   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15011                        DAG.getConstant(ArgMode, dl, MVT::i8),
15012                        DAG.getConstant(Align, dl, MVT::i32)};
15013   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
15014   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15015                                           VTs, InstOps, MVT::i64,
15016                                           MachinePointerInfo(SV),
15017                                           /*Align=*/0,
15018                                           /*Volatile=*/false,
15019                                           /*ReadMem=*/true,
15020                                           /*WriteMem=*/true);
15021   Chain = VAARG.getValue(1);
15022
15023   // Load the next argument and return it
15024   return DAG.getLoad(ArgVT, dl,
15025                      Chain,
15026                      VAARG,
15027                      MachinePointerInfo(),
15028                      false, false, false, 0);
15029 }
15030
15031 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15032                            SelectionDAG &DAG) {
15033   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15034   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15035   SDValue Chain = Op.getOperand(0);
15036   SDValue DstPtr = Op.getOperand(1);
15037   SDValue SrcPtr = Op.getOperand(2);
15038   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15039   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15040   SDLoc DL(Op);
15041
15042   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15043                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15044                        false, false,
15045                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15046 }
15047
15048 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15049 // amount is a constant. Takes immediate version of shift as input.
15050 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15051                                           SDValue SrcOp, uint64_t ShiftAmt,
15052                                           SelectionDAG &DAG) {
15053   MVT ElementType = VT.getVectorElementType();
15054
15055   // Fold this packed shift into its first operand if ShiftAmt is 0.
15056   if (ShiftAmt == 0)
15057     return SrcOp;
15058
15059   // Check for ShiftAmt >= element width
15060   if (ShiftAmt >= ElementType.getSizeInBits()) {
15061     if (Opc == X86ISD::VSRAI)
15062       ShiftAmt = ElementType.getSizeInBits() - 1;
15063     else
15064       return DAG.getConstant(0, dl, VT);
15065   }
15066
15067   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15068          && "Unknown target vector shift-by-constant node");
15069
15070   // Fold this packed vector shift into a build vector if SrcOp is a
15071   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15072   if (VT == SrcOp.getSimpleValueType() &&
15073       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15074     SmallVector<SDValue, 8> Elts;
15075     unsigned NumElts = SrcOp->getNumOperands();
15076     ConstantSDNode *ND;
15077
15078     switch(Opc) {
15079     default: llvm_unreachable(nullptr);
15080     case X86ISD::VSHLI:
15081       for (unsigned i=0; i!=NumElts; ++i) {
15082         SDValue CurrentOp = SrcOp->getOperand(i);
15083         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15084           Elts.push_back(CurrentOp);
15085           continue;
15086         }
15087         ND = cast<ConstantSDNode>(CurrentOp);
15088         const APInt &C = ND->getAPIntValue();
15089         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15090       }
15091       break;
15092     case X86ISD::VSRLI:
15093       for (unsigned i=0; i!=NumElts; ++i) {
15094         SDValue CurrentOp = SrcOp->getOperand(i);
15095         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15096           Elts.push_back(CurrentOp);
15097           continue;
15098         }
15099         ND = cast<ConstantSDNode>(CurrentOp);
15100         const APInt &C = ND->getAPIntValue();
15101         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15102       }
15103       break;
15104     case X86ISD::VSRAI:
15105       for (unsigned i=0; i!=NumElts; ++i) {
15106         SDValue CurrentOp = SrcOp->getOperand(i);
15107         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15108           Elts.push_back(CurrentOp);
15109           continue;
15110         }
15111         ND = cast<ConstantSDNode>(CurrentOp);
15112         const APInt &C = ND->getAPIntValue();
15113         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15114       }
15115       break;
15116     }
15117
15118     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15119   }
15120
15121   return DAG.getNode(Opc, dl, VT, SrcOp,
15122                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15123 }
15124
15125 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15126 // may or may not be a constant. Takes immediate version of shift as input.
15127 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15128                                    SDValue SrcOp, SDValue ShAmt,
15129                                    SelectionDAG &DAG) {
15130   MVT SVT = ShAmt.getSimpleValueType();
15131   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15132
15133   // Catch shift-by-constant.
15134   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15135     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15136                                       CShAmt->getZExtValue(), DAG);
15137
15138   // Change opcode to non-immediate version
15139   switch (Opc) {
15140     default: llvm_unreachable("Unknown target vector shift node");
15141     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15142     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15143     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15144   }
15145
15146   const X86Subtarget &Subtarget =
15147       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15148   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15149       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15150     // Let the shuffle legalizer expand this shift amount node.
15151     SDValue Op0 = ShAmt.getOperand(0);
15152     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15153     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15154   } else {
15155     // Need to build a vector containing shift amount.
15156     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15157     SmallVector<SDValue, 4> ShOps;
15158     ShOps.push_back(ShAmt);
15159     if (SVT == MVT::i32) {
15160       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15161       ShOps.push_back(DAG.getUNDEF(SVT));
15162     }
15163     ShOps.push_back(DAG.getUNDEF(SVT));
15164
15165     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15166     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15167   }
15168
15169   // The return type has to be a 128-bit type with the same element
15170   // type as the input type.
15171   MVT EltVT = VT.getVectorElementType();
15172   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15173
15174   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15175   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15176 }
15177
15178 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15179 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15180 /// necessary casting for \p Mask when lowering masking intrinsics.
15181 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15182                                     SDValue PreservedSrc,
15183                                     const X86Subtarget *Subtarget,
15184                                     SelectionDAG &DAG) {
15185     EVT VT = Op.getValueType();
15186     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15187                                   MVT::i1, VT.getVectorNumElements());
15188     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15189                                      Mask.getValueType().getSizeInBits());
15190     SDLoc dl(Op);
15191
15192     assert(MaskVT.isSimple() && "invalid mask type");
15193
15194     if (isAllOnes(Mask))
15195       return Op;
15196
15197     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15198     // are extracted by EXTRACT_SUBVECTOR.
15199     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15200                                 DAG.getBitcast(BitcastVT, Mask),
15201                                 DAG.getIntPtrConstant(0, dl));
15202
15203     switch (Op.getOpcode()) {
15204       default: break;
15205       case X86ISD::PCMPEQM:
15206       case X86ISD::PCMPGTM:
15207       case X86ISD::CMPM:
15208       case X86ISD::CMPMU:
15209         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15210     }
15211     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15212       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15213     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15214 }
15215
15216 /// \brief Creates an SDNode for a predicated scalar operation.
15217 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15218 /// The mask is comming as MVT::i8 and it should be truncated
15219 /// to MVT::i1 while lowering masking intrinsics.
15220 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15221 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15222 /// a scalar instruction.
15223 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15224                                     SDValue PreservedSrc,
15225                                     const X86Subtarget *Subtarget,
15226                                     SelectionDAG &DAG) {
15227     if (isAllOnes(Mask))
15228       return Op;
15229
15230     EVT VT = Op.getValueType();
15231     SDLoc dl(Op);
15232     // The mask should be of type MVT::i1
15233     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15234
15235     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15236       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15237     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15238 }
15239
15240 static int getSEHRegistrationNodeSize(const Function *Fn) {
15241   if (!Fn->hasPersonalityFn())
15242     report_fatal_error(
15243         "querying registration node size for function without personality");
15244   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15245   // WinEHStatePass for the full struct definition.
15246   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15247   case EHPersonality::MSVC_X86SEH: return 24;
15248   case EHPersonality::MSVC_CXX: return 16;
15249   default: break;
15250   }
15251   report_fatal_error("can only recover FP for MSVC EH personality functions");
15252 }
15253
15254 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15255 /// function or when returning to a parent frame after catching an exception, we
15256 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15257 /// Here's the math:
15258 ///   RegNodeBase = EntryEBP - RegNodeSize
15259 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15260 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15261 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15262 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15263                                    SDValue EntryEBP) {
15264   MachineFunction &MF = DAG.getMachineFunction();
15265   SDLoc dl;
15266
15267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15268   MVT PtrVT = TLI.getPointerTy();
15269
15270   // It's possible that the parent function no longer has a personality function
15271   // if the exceptional code was optimized away, in which case we just return
15272   // the incoming EBP.
15273   if (!Fn->hasPersonalityFn())
15274     return EntryEBP;
15275
15276   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15277
15278   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15279   // registration.
15280   MCSymbol *OffsetSym =
15281       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15282           GlobalValue::getRealLinkageName(Fn->getName()));
15283   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15284   SDValue RegNodeFrameOffset =
15285       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15286
15287   // RegNodeBase = EntryEBP - RegNodeSize
15288   // ParentFP = RegNodeBase - RegNodeFrameOffset
15289   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15290                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15291   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15292 }
15293
15294 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15295                                        SelectionDAG &DAG) {
15296   SDLoc dl(Op);
15297   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15298   EVT VT = Op.getValueType();
15299   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15300   if (IntrData) {
15301     switch(IntrData->Type) {
15302     case INTR_TYPE_1OP:
15303       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15304     case INTR_TYPE_2OP:
15305       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15306         Op.getOperand(2));
15307     case INTR_TYPE_3OP:
15308       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15309         Op.getOperand(2), Op.getOperand(3));
15310     case INTR_TYPE_4OP:
15311       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15312         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15313     case INTR_TYPE_1OP_MASK_RM: {
15314       SDValue Src = Op.getOperand(1);
15315       SDValue PassThru = Op.getOperand(2);
15316       SDValue Mask = Op.getOperand(3);
15317       SDValue RoundingMode;
15318       if (Op.getNumOperands() == 4)
15319         RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15320       else
15321         RoundingMode = Op.getOperand(4);
15322       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15323       if (IntrWithRoundingModeOpcode != 0) {
15324         unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15325         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15326           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15327                                       dl, Op.getValueType(), Src, RoundingMode),
15328                                       Mask, PassThru, Subtarget, DAG);
15329       }
15330       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15331                                               RoundingMode),
15332                                   Mask, PassThru, Subtarget, DAG);
15333     }
15334     case INTR_TYPE_1OP_MASK: {
15335       SDValue Src = Op.getOperand(1);
15336       SDValue Passthru = Op.getOperand(2);
15337       SDValue Mask = Op.getOperand(3);
15338       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15339                                   Mask, Passthru, Subtarget, DAG);
15340     }
15341     case INTR_TYPE_SCALAR_MASK_RM: {
15342       SDValue Src1 = Op.getOperand(1);
15343       SDValue Src2 = Op.getOperand(2);
15344       SDValue Src0 = Op.getOperand(3);
15345       SDValue Mask = Op.getOperand(4);
15346       // There are 2 kinds of intrinsics in this group:
15347       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15348       // (2) With rounding mode and sae - 7 operands.
15349       if (Op.getNumOperands() == 6) {
15350         SDValue Sae  = Op.getOperand(5);
15351         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15352         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15353                                                 Sae),
15354                                     Mask, Src0, Subtarget, DAG);
15355       }
15356       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15357       SDValue RoundingMode  = Op.getOperand(5);
15358       SDValue Sae  = Op.getOperand(6);
15359       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15360                                               RoundingMode, Sae),
15361                                   Mask, Src0, Subtarget, DAG);
15362     }
15363     case INTR_TYPE_2OP_MASK: {
15364       SDValue Src1 = Op.getOperand(1);
15365       SDValue Src2 = Op.getOperand(2);
15366       SDValue PassThru = Op.getOperand(3);
15367       SDValue Mask = Op.getOperand(4);
15368       // We specify 2 possible opcodes for intrinsics with rounding modes.
15369       // First, we check if the intrinsic may have non-default rounding mode,
15370       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15371       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15372       if (IntrWithRoundingModeOpcode != 0) {
15373         SDValue Rnd = Op.getOperand(5);
15374         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15375         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15376           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15377                                       dl, Op.getValueType(),
15378                                       Src1, Src2, Rnd),
15379                                       Mask, PassThru, Subtarget, DAG);
15380         }
15381       }
15382       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15383                                               Src1,Src2),
15384                                   Mask, PassThru, Subtarget, DAG);
15385     }
15386     case INTR_TYPE_2OP_MASK_RM: {
15387       SDValue Src1 = Op.getOperand(1);
15388       SDValue Src2 = Op.getOperand(2);
15389       SDValue PassThru = Op.getOperand(3);
15390       SDValue Mask = Op.getOperand(4);
15391       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15392       // First, we check if the intrinsic have rounding mode (6 operands),
15393       // if not, we set rounding mode to "current".
15394       SDValue Rnd;
15395       if (Op.getNumOperands() == 6)
15396         Rnd = Op.getOperand(5);
15397       else 
15398         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15399       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15400                                               Src1, Src2, Rnd),
15401                                   Mask, PassThru, Subtarget, DAG);
15402     }
15403     case INTR_TYPE_3OP_MASK: {
15404       SDValue Src1 = Op.getOperand(1);
15405       SDValue Src2 = Op.getOperand(2);
15406       SDValue Src3 = Op.getOperand(3);
15407       SDValue PassThru = Op.getOperand(4);
15408       SDValue Mask = Op.getOperand(5);
15409       // We specify 2 possible opcodes for intrinsics with rounding modes.
15410       // First, we check if the intrinsic may have non-default rounding mode,
15411       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15412       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15413       if (IntrWithRoundingModeOpcode != 0) {
15414         SDValue Rnd = Op.getOperand(6);
15415         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15416         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15417           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15418                                       dl, Op.getValueType(),
15419                                       Src1, Src2, Src3, Rnd),
15420                                       Mask, PassThru, Subtarget, DAG);
15421         }
15422       }
15423       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15424                                               Src1, Src2, Src3),
15425                                   Mask, PassThru, Subtarget, DAG);
15426     }
15427     case VPERM_3OP_MASKZ: 
15428     case VPERM_3OP_MASK:
15429     case FMA_OP_MASK3:
15430     case FMA_OP_MASKZ:
15431     case FMA_OP_MASK: {
15432       SDValue Src1 = Op.getOperand(1);
15433       SDValue Src2 = Op.getOperand(2);
15434       SDValue Src3 = Op.getOperand(3);
15435       SDValue Mask = Op.getOperand(4);
15436       EVT VT = Op.getValueType();
15437       SDValue PassThru = SDValue();
15438
15439       // set PassThru element
15440       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15441         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15442       else if (IntrData->Type == FMA_OP_MASK3)
15443         PassThru = Src3;
15444       else
15445         PassThru = Src1;
15446
15447       // We specify 2 possible opcodes for intrinsics with rounding modes.
15448       // First, we check if the intrinsic may have non-default rounding mode,
15449       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15450       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15451       if (IntrWithRoundingModeOpcode != 0) {
15452         SDValue Rnd = Op.getOperand(5);
15453         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15454             X86::STATIC_ROUNDING::CUR_DIRECTION)
15455           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15456                                                   dl, Op.getValueType(),
15457                                                   Src1, Src2, Src3, Rnd),
15458                                       Mask, PassThru, Subtarget, DAG);
15459       }
15460       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15461                                               dl, Op.getValueType(),
15462                                               Src1, Src2, Src3),
15463                                   Mask, PassThru, Subtarget, DAG);
15464     }
15465     case CMP_MASK:
15466     case CMP_MASK_CC: {
15467       // Comparison intrinsics with masks.
15468       // Example of transformation:
15469       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15470       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15471       // (i8 (bitcast
15472       //   (v8i1 (insert_subvector undef,
15473       //           (v2i1 (and (PCMPEQM %a, %b),
15474       //                      (extract_subvector
15475       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15476       EVT VT = Op.getOperand(1).getValueType();
15477       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15478                                     VT.getVectorNumElements());
15479       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15480       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15481                                        Mask.getValueType().getSizeInBits());
15482       SDValue Cmp;
15483       if (IntrData->Type == CMP_MASK_CC) {
15484         SDValue CC = Op.getOperand(3);
15485         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15486         // We specify 2 possible opcodes for intrinsics with rounding modes.
15487         // First, we check if the intrinsic may have non-default rounding mode,
15488         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15489         if (IntrData->Opc1 != 0) {
15490           SDValue Rnd = Op.getOperand(5);
15491           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15492               X86::STATIC_ROUNDING::CUR_DIRECTION)
15493             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15494                               Op.getOperand(2), CC, Rnd);
15495         }
15496         //default rounding mode
15497         if(!Cmp.getNode())
15498             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15499                               Op.getOperand(2), CC);
15500
15501       } else {
15502         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15503         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15504                           Op.getOperand(2));
15505       }
15506       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15507                                              DAG.getTargetConstant(0, dl,
15508                                                                    MaskVT),
15509                                              Subtarget, DAG);
15510       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15511                                 DAG.getUNDEF(BitcastVT), CmpMask,
15512                                 DAG.getIntPtrConstant(0, dl));
15513       return DAG.getBitcast(Op.getValueType(), Res);
15514     }
15515     case COMI: { // Comparison intrinsics
15516       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15517       SDValue LHS = Op.getOperand(1);
15518       SDValue RHS = Op.getOperand(2);
15519       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15520       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15521       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15522       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15523                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15524       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15525     }
15526     case VSHIFT:
15527       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15528                                  Op.getOperand(1), Op.getOperand(2), DAG);
15529     case VSHIFT_MASK:
15530       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15531                                                       Op.getSimpleValueType(),
15532                                                       Op.getOperand(1),
15533                                                       Op.getOperand(2), DAG),
15534                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15535                                   DAG);
15536     case COMPRESS_EXPAND_IN_REG: {
15537       SDValue Mask = Op.getOperand(3);
15538       SDValue DataToCompress = Op.getOperand(1);
15539       SDValue PassThru = Op.getOperand(2);
15540       if (isAllOnes(Mask)) // return data as is
15541         return Op.getOperand(1);
15542
15543       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15544                                               DataToCompress),
15545                                   Mask, PassThru, Subtarget, DAG);
15546     }
15547     case BLEND: {
15548       SDValue Mask = Op.getOperand(3);
15549       EVT VT = Op.getValueType();
15550       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15551                                     VT.getVectorNumElements());
15552       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15553                                        Mask.getValueType().getSizeInBits());
15554       SDLoc dl(Op);
15555       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15556                                   DAG.getBitcast(BitcastVT, Mask),
15557                                   DAG.getIntPtrConstant(0, dl));
15558       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15559                          Op.getOperand(2));
15560     }
15561     default:
15562       break;
15563     }
15564   }
15565
15566   switch (IntNo) {
15567   default: return SDValue();    // Don't custom lower most intrinsics.
15568
15569   case Intrinsic::x86_avx2_permd:
15570   case Intrinsic::x86_avx2_permps:
15571     // Operands intentionally swapped. Mask is last operand to intrinsic,
15572     // but second operand for node/instruction.
15573     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15574                        Op.getOperand(2), Op.getOperand(1));
15575
15576   // ptest and testp intrinsics. The intrinsic these come from are designed to
15577   // return an integer value, not just an instruction so lower it to the ptest
15578   // or testp pattern and a setcc for the result.
15579   case Intrinsic::x86_sse41_ptestz:
15580   case Intrinsic::x86_sse41_ptestc:
15581   case Intrinsic::x86_sse41_ptestnzc:
15582   case Intrinsic::x86_avx_ptestz_256:
15583   case Intrinsic::x86_avx_ptestc_256:
15584   case Intrinsic::x86_avx_ptestnzc_256:
15585   case Intrinsic::x86_avx_vtestz_ps:
15586   case Intrinsic::x86_avx_vtestc_ps:
15587   case Intrinsic::x86_avx_vtestnzc_ps:
15588   case Intrinsic::x86_avx_vtestz_pd:
15589   case Intrinsic::x86_avx_vtestc_pd:
15590   case Intrinsic::x86_avx_vtestnzc_pd:
15591   case Intrinsic::x86_avx_vtestz_ps_256:
15592   case Intrinsic::x86_avx_vtestc_ps_256:
15593   case Intrinsic::x86_avx_vtestnzc_ps_256:
15594   case Intrinsic::x86_avx_vtestz_pd_256:
15595   case Intrinsic::x86_avx_vtestc_pd_256:
15596   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15597     bool IsTestPacked = false;
15598     unsigned X86CC;
15599     switch (IntNo) {
15600     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15601     case Intrinsic::x86_avx_vtestz_ps:
15602     case Intrinsic::x86_avx_vtestz_pd:
15603     case Intrinsic::x86_avx_vtestz_ps_256:
15604     case Intrinsic::x86_avx_vtestz_pd_256:
15605       IsTestPacked = true; // Fallthrough
15606     case Intrinsic::x86_sse41_ptestz:
15607     case Intrinsic::x86_avx_ptestz_256:
15608       // ZF = 1
15609       X86CC = X86::COND_E;
15610       break;
15611     case Intrinsic::x86_avx_vtestc_ps:
15612     case Intrinsic::x86_avx_vtestc_pd:
15613     case Intrinsic::x86_avx_vtestc_ps_256:
15614     case Intrinsic::x86_avx_vtestc_pd_256:
15615       IsTestPacked = true; // Fallthrough
15616     case Intrinsic::x86_sse41_ptestc:
15617     case Intrinsic::x86_avx_ptestc_256:
15618       // CF = 1
15619       X86CC = X86::COND_B;
15620       break;
15621     case Intrinsic::x86_avx_vtestnzc_ps:
15622     case Intrinsic::x86_avx_vtestnzc_pd:
15623     case Intrinsic::x86_avx_vtestnzc_ps_256:
15624     case Intrinsic::x86_avx_vtestnzc_pd_256:
15625       IsTestPacked = true; // Fallthrough
15626     case Intrinsic::x86_sse41_ptestnzc:
15627     case Intrinsic::x86_avx_ptestnzc_256:
15628       // ZF and CF = 0
15629       X86CC = X86::COND_A;
15630       break;
15631     }
15632
15633     SDValue LHS = Op.getOperand(1);
15634     SDValue RHS = Op.getOperand(2);
15635     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15636     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15637     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15638     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15639     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15640   }
15641   case Intrinsic::x86_avx512_kortestz_w:
15642   case Intrinsic::x86_avx512_kortestc_w: {
15643     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15644     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15645     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15646     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15647     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15648     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15649     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15650   }
15651
15652   case Intrinsic::x86_sse42_pcmpistria128:
15653   case Intrinsic::x86_sse42_pcmpestria128:
15654   case Intrinsic::x86_sse42_pcmpistric128:
15655   case Intrinsic::x86_sse42_pcmpestric128:
15656   case Intrinsic::x86_sse42_pcmpistrio128:
15657   case Intrinsic::x86_sse42_pcmpestrio128:
15658   case Intrinsic::x86_sse42_pcmpistris128:
15659   case Intrinsic::x86_sse42_pcmpestris128:
15660   case Intrinsic::x86_sse42_pcmpistriz128:
15661   case Intrinsic::x86_sse42_pcmpestriz128: {
15662     unsigned Opcode;
15663     unsigned X86CC;
15664     switch (IntNo) {
15665     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15666     case Intrinsic::x86_sse42_pcmpistria128:
15667       Opcode = X86ISD::PCMPISTRI;
15668       X86CC = X86::COND_A;
15669       break;
15670     case Intrinsic::x86_sse42_pcmpestria128:
15671       Opcode = X86ISD::PCMPESTRI;
15672       X86CC = X86::COND_A;
15673       break;
15674     case Intrinsic::x86_sse42_pcmpistric128:
15675       Opcode = X86ISD::PCMPISTRI;
15676       X86CC = X86::COND_B;
15677       break;
15678     case Intrinsic::x86_sse42_pcmpestric128:
15679       Opcode = X86ISD::PCMPESTRI;
15680       X86CC = X86::COND_B;
15681       break;
15682     case Intrinsic::x86_sse42_pcmpistrio128:
15683       Opcode = X86ISD::PCMPISTRI;
15684       X86CC = X86::COND_O;
15685       break;
15686     case Intrinsic::x86_sse42_pcmpestrio128:
15687       Opcode = X86ISD::PCMPESTRI;
15688       X86CC = X86::COND_O;
15689       break;
15690     case Intrinsic::x86_sse42_pcmpistris128:
15691       Opcode = X86ISD::PCMPISTRI;
15692       X86CC = X86::COND_S;
15693       break;
15694     case Intrinsic::x86_sse42_pcmpestris128:
15695       Opcode = X86ISD::PCMPESTRI;
15696       X86CC = X86::COND_S;
15697       break;
15698     case Intrinsic::x86_sse42_pcmpistriz128:
15699       Opcode = X86ISD::PCMPISTRI;
15700       X86CC = X86::COND_E;
15701       break;
15702     case Intrinsic::x86_sse42_pcmpestriz128:
15703       Opcode = X86ISD::PCMPESTRI;
15704       X86CC = X86::COND_E;
15705       break;
15706     }
15707     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15708     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15709     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15710     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15711                                 DAG.getConstant(X86CC, dl, MVT::i8),
15712                                 SDValue(PCMP.getNode(), 1));
15713     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15714   }
15715
15716   case Intrinsic::x86_sse42_pcmpistri128:
15717   case Intrinsic::x86_sse42_pcmpestri128: {
15718     unsigned Opcode;
15719     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15720       Opcode = X86ISD::PCMPISTRI;
15721     else
15722       Opcode = X86ISD::PCMPESTRI;
15723
15724     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15725     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15726     return DAG.getNode(Opcode, dl, VTs, NewOps);
15727   }
15728
15729   case Intrinsic::x86_seh_lsda: {
15730     // Compute the symbol for the LSDA. We know it'll get emitted later.
15731     MachineFunction &MF = DAG.getMachineFunction();
15732     SDValue Op1 = Op.getOperand(1);
15733     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15734     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15735         GlobalValue::getRealLinkageName(Fn->getName()));
15736
15737     // Generate a simple absolute symbol reference. This intrinsic is only
15738     // supported on 32-bit Windows, which isn't PIC.
15739     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15740     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15741   }
15742
15743   case Intrinsic::x86_seh_recoverfp: {
15744     SDValue FnOp = Op.getOperand(1);
15745     SDValue IncomingFPOp = Op.getOperand(2);
15746     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15747     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15748     if (!Fn)
15749       report_fatal_error(
15750           "llvm.x86.seh.recoverfp must take a function as the first argument");
15751     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15752   }
15753
15754   case Intrinsic::localaddress: {
15755     // Returns one of the stack, base, or frame pointer registers, depending on
15756     // which is used to reference local variables.
15757     MachineFunction &MF = DAG.getMachineFunction();
15758     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15759     unsigned Reg;
15760     if (RegInfo->hasBasePointer(MF))
15761       Reg = RegInfo->getBaseRegister();
15762     else // This function handles the SP or FP case.
15763       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15764     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15765   }
15766   }
15767 }
15768
15769 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15770                               SDValue Src, SDValue Mask, SDValue Base,
15771                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15772                               const X86Subtarget * Subtarget) {
15773   SDLoc dl(Op);
15774   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15775   if (!C)
15776     llvm_unreachable("Invalid scale type");
15777   unsigned ScaleVal = C->getZExtValue();
15778   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15779     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15780
15781   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15782   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15783                              Index.getSimpleValueType().getVectorNumElements());
15784   SDValue MaskInReg;
15785   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15786   if (MaskC)
15787     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15788   else {
15789     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15790                                      Mask.getValueType().getSizeInBits());
15791
15792     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15793     // are extracted by EXTRACT_SUBVECTOR.
15794     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15795                             DAG.getBitcast(BitcastVT, Mask),
15796                             DAG.getIntPtrConstant(0, dl));
15797   }
15798   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15799   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15800   SDValue Segment = DAG.getRegister(0, MVT::i32);
15801   if (Src.getOpcode() == ISD::UNDEF)
15802     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15803   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15804   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15805   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15806   return DAG.getMergeValues(RetOps, dl);
15807 }
15808
15809 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15810                                SDValue Src, SDValue Mask, SDValue Base,
15811                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15812   SDLoc dl(Op);
15813   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15814   if (!C)
15815     llvm_unreachable("Invalid scale type");
15816   unsigned ScaleVal = C->getZExtValue();
15817   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15818     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15819
15820   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15821   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15822   SDValue Segment = DAG.getRegister(0, MVT::i32);
15823   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15824                              Index.getSimpleValueType().getVectorNumElements());
15825   SDValue MaskInReg;
15826   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15827   if (MaskC)
15828     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15829   else {
15830     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15831                                      Mask.getValueType().getSizeInBits());
15832
15833     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15834     // are extracted by EXTRACT_SUBVECTOR.
15835     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15836                             DAG.getBitcast(BitcastVT, Mask),
15837                             DAG.getIntPtrConstant(0, dl));
15838   }
15839   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15840   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15841   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15842   return SDValue(Res, 1);
15843 }
15844
15845 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15846                                SDValue Mask, SDValue Base, SDValue Index,
15847                                SDValue ScaleOp, SDValue Chain) {
15848   SDLoc dl(Op);
15849   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15850   assert(C && "Invalid scale type");
15851   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15852   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15853   SDValue Segment = DAG.getRegister(0, MVT::i32);
15854   EVT MaskVT =
15855     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15856   SDValue MaskInReg;
15857   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15858   if (MaskC)
15859     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15860   else
15861     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15862   //SDVTList VTs = DAG.getVTList(MVT::Other);
15863   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15864   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15865   return SDValue(Res, 0);
15866 }
15867
15868 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15869 // read performance monitor counters (x86_rdpmc).
15870 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15871                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15872                               SmallVectorImpl<SDValue> &Results) {
15873   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15874   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15875   SDValue LO, HI;
15876
15877   // The ECX register is used to select the index of the performance counter
15878   // to read.
15879   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15880                                    N->getOperand(2));
15881   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15882
15883   // Reads the content of a 64-bit performance counter and returns it in the
15884   // registers EDX:EAX.
15885   if (Subtarget->is64Bit()) {
15886     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15887     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15888                             LO.getValue(2));
15889   } else {
15890     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15891     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15892                             LO.getValue(2));
15893   }
15894   Chain = HI.getValue(1);
15895
15896   if (Subtarget->is64Bit()) {
15897     // The EAX register is loaded with the low-order 32 bits. The EDX register
15898     // is loaded with the supported high-order bits of the counter.
15899     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15900                               DAG.getConstant(32, DL, MVT::i8));
15901     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15902     Results.push_back(Chain);
15903     return;
15904   }
15905
15906   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15907   SDValue Ops[] = { LO, HI };
15908   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15909   Results.push_back(Pair);
15910   Results.push_back(Chain);
15911 }
15912
15913 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15914 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15915 // also used to custom lower READCYCLECOUNTER nodes.
15916 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15917                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15918                               SmallVectorImpl<SDValue> &Results) {
15919   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15920   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15921   SDValue LO, HI;
15922
15923   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15924   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15925   // and the EAX register is loaded with the low-order 32 bits.
15926   if (Subtarget->is64Bit()) {
15927     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15928     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15929                             LO.getValue(2));
15930   } else {
15931     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15932     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15933                             LO.getValue(2));
15934   }
15935   SDValue Chain = HI.getValue(1);
15936
15937   if (Opcode == X86ISD::RDTSCP_DAG) {
15938     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15939
15940     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15941     // the ECX register. Add 'ecx' explicitly to the chain.
15942     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15943                                      HI.getValue(2));
15944     // Explicitly store the content of ECX at the location passed in input
15945     // to the 'rdtscp' intrinsic.
15946     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15947                          MachinePointerInfo(), false, false, 0);
15948   }
15949
15950   if (Subtarget->is64Bit()) {
15951     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15952     // the EAX register is loaded with the low-order 32 bits.
15953     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15954                               DAG.getConstant(32, DL, MVT::i8));
15955     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15956     Results.push_back(Chain);
15957     return;
15958   }
15959
15960   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15961   SDValue Ops[] = { LO, HI };
15962   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15963   Results.push_back(Pair);
15964   Results.push_back(Chain);
15965 }
15966
15967 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15968                                      SelectionDAG &DAG) {
15969   SmallVector<SDValue, 2> Results;
15970   SDLoc DL(Op);
15971   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15972                           Results);
15973   return DAG.getMergeValues(Results, DL);
15974 }
15975
15976 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
15977                                     SelectionDAG &DAG) {
15978   MachineFunction &MF = DAG.getMachineFunction();
15979   const Function *Fn = MF.getFunction();
15980   SDLoc dl(Op);
15981   SDValue Chain = Op.getOperand(0);
15982
15983   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
15984          "using llvm.x86.seh.restoreframe requires a frame pointer");
15985
15986   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15987   MVT VT = TLI.getPointerTy();
15988
15989   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15990   unsigned FrameReg =
15991       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15992   unsigned SPReg = RegInfo->getStackRegister();
15993   unsigned SlotSize = RegInfo->getSlotSize();
15994
15995   // Get incoming EBP.
15996   SDValue IncomingEBP =
15997       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
15998
15999   // SP is saved in the first field of every registration node, so load
16000   // [EBP-RegNodeSize] into SP.
16001   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16002   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16003                                DAG.getConstant(-RegNodeSize, dl, VT));
16004   SDValue NewSP =
16005       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16006                   false, VT.getScalarSizeInBits() / 8);
16007   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16008
16009   if (!RegInfo->needsStackRealignment(MF)) {
16010     // Adjust EBP to point back to the original frame position.
16011     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16012     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16013   } else {
16014     assert(RegInfo->hasBasePointer(MF) &&
16015            "functions with Win32 EH must use frame or base pointer register");
16016
16017     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16018     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16019     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16020
16021     // Reload the spilled EBP value, now that the stack and base pointers are
16022     // set up.
16023     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16024     X86FI->setHasSEHFramePtrSave(true);
16025     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16026     X86FI->setSEHFramePtrSaveIndex(FI);
16027     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16028                                 MachinePointerInfo(), false, false, false,
16029                                 VT.getScalarSizeInBits() / 8);
16030     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16031   }
16032
16033   return Chain;
16034 }
16035
16036 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16037                                       SelectionDAG &DAG) {
16038   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16039
16040   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16041   if (!IntrData) {
16042     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16043       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16044     return SDValue();
16045   }
16046
16047   SDLoc dl(Op);
16048   switch(IntrData->Type) {
16049   default:
16050     llvm_unreachable("Unknown Intrinsic Type");
16051     break;
16052   case RDSEED:
16053   case RDRAND: {
16054     // Emit the node with the right value type.
16055     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16056     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16057
16058     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16059     // Otherwise return the value from Rand, which is always 0, casted to i32.
16060     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16061                       DAG.getConstant(1, dl, Op->getValueType(1)),
16062                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16063                       SDValue(Result.getNode(), 1) };
16064     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16065                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16066                                   Ops);
16067
16068     // Return { result, isValid, chain }.
16069     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16070                        SDValue(Result.getNode(), 2));
16071   }
16072   case GATHER: {
16073   //gather(v1, mask, index, base, scale);
16074     SDValue Chain = Op.getOperand(0);
16075     SDValue Src   = Op.getOperand(2);
16076     SDValue Base  = Op.getOperand(3);
16077     SDValue Index = Op.getOperand(4);
16078     SDValue Mask  = Op.getOperand(5);
16079     SDValue Scale = Op.getOperand(6);
16080     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16081                          Chain, Subtarget);
16082   }
16083   case SCATTER: {
16084   //scatter(base, mask, index, v1, scale);
16085     SDValue Chain = Op.getOperand(0);
16086     SDValue Base  = Op.getOperand(2);
16087     SDValue Mask  = Op.getOperand(3);
16088     SDValue Index = Op.getOperand(4);
16089     SDValue Src   = Op.getOperand(5);
16090     SDValue Scale = Op.getOperand(6);
16091     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16092                           Scale, Chain);
16093   }
16094   case PREFETCH: {
16095     SDValue Hint = Op.getOperand(6);
16096     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16097     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16098     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16099     SDValue Chain = Op.getOperand(0);
16100     SDValue Mask  = Op.getOperand(2);
16101     SDValue Index = Op.getOperand(3);
16102     SDValue Base  = Op.getOperand(4);
16103     SDValue Scale = Op.getOperand(5);
16104     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16105   }
16106   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16107   case RDTSC: {
16108     SmallVector<SDValue, 2> Results;
16109     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16110                             Results);
16111     return DAG.getMergeValues(Results, dl);
16112   }
16113   // Read Performance Monitoring Counters.
16114   case RDPMC: {
16115     SmallVector<SDValue, 2> Results;
16116     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16117     return DAG.getMergeValues(Results, dl);
16118   }
16119   // XTEST intrinsics.
16120   case XTEST: {
16121     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16122     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16123     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16124                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16125                                 InTrans);
16126     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16127     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16128                        Ret, SDValue(InTrans.getNode(), 1));
16129   }
16130   // ADC/ADCX/SBB
16131   case ADX: {
16132     SmallVector<SDValue, 2> Results;
16133     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16134     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16135     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16136                                 DAG.getConstant(-1, dl, MVT::i8));
16137     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16138                               Op.getOperand(4), GenCF.getValue(1));
16139     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16140                                  Op.getOperand(5), MachinePointerInfo(),
16141                                  false, false, 0);
16142     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16143                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16144                                 Res.getValue(1));
16145     Results.push_back(SetCC);
16146     Results.push_back(Store);
16147     return DAG.getMergeValues(Results, dl);
16148   }
16149   case COMPRESS_TO_MEM: {
16150     SDLoc dl(Op);
16151     SDValue Mask = Op.getOperand(4);
16152     SDValue DataToCompress = Op.getOperand(3);
16153     SDValue Addr = Op.getOperand(2);
16154     SDValue Chain = Op.getOperand(0);
16155
16156     EVT VT = DataToCompress.getValueType();
16157     if (isAllOnes(Mask)) // return just a store
16158       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16159                           MachinePointerInfo(), false, false,
16160                           VT.getScalarSizeInBits()/8);
16161
16162     SDValue Compressed =
16163       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16164                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16165     return DAG.getStore(Chain, dl, Compressed, Addr,
16166                         MachinePointerInfo(), false, false,
16167                         VT.getScalarSizeInBits()/8);
16168   }
16169   case EXPAND_FROM_MEM: {
16170     SDLoc dl(Op);
16171     SDValue Mask = Op.getOperand(4);
16172     SDValue PassThru = Op.getOperand(3);
16173     SDValue Addr = Op.getOperand(2);
16174     SDValue Chain = Op.getOperand(0);
16175     EVT VT = Op.getValueType();
16176
16177     if (isAllOnes(Mask)) // return just a load
16178       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16179                          false, VT.getScalarSizeInBits()/8);
16180
16181     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16182                                        false, false, false,
16183                                        VT.getScalarSizeInBits()/8);
16184
16185     SDValue Results[] = {
16186       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16187                            Mask, PassThru, Subtarget, DAG), Chain};
16188     return DAG.getMergeValues(Results, dl);
16189   }
16190   }
16191 }
16192
16193 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16194                                            SelectionDAG &DAG) const {
16195   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16196   MFI->setReturnAddressIsTaken(true);
16197
16198   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16199     return SDValue();
16200
16201   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16202   SDLoc dl(Op);
16203   EVT PtrVT = getPointerTy();
16204
16205   if (Depth > 0) {
16206     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16207     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16208     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16209     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16210                        DAG.getNode(ISD::ADD, dl, PtrVT,
16211                                    FrameAddr, Offset),
16212                        MachinePointerInfo(), false, false, false, 0);
16213   }
16214
16215   // Just load the return address.
16216   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16217   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16218                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16219 }
16220
16221 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16222   MachineFunction &MF = DAG.getMachineFunction();
16223   MachineFrameInfo *MFI = MF.getFrameInfo();
16224   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16225   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16226   EVT VT = Op.getValueType();
16227
16228   MFI->setFrameAddressIsTaken(true);
16229
16230   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16231     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16232     // is not possible to crawl up the stack without looking at the unwind codes
16233     // simultaneously.
16234     int FrameAddrIndex = FuncInfo->getFAIndex();
16235     if (!FrameAddrIndex) {
16236       // Set up a frame object for the return address.
16237       unsigned SlotSize = RegInfo->getSlotSize();
16238       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16239           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16240       FuncInfo->setFAIndex(FrameAddrIndex);
16241     }
16242     return DAG.getFrameIndex(FrameAddrIndex, VT);
16243   }
16244
16245   unsigned FrameReg =
16246       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16247   SDLoc dl(Op);  // FIXME probably not meaningful
16248   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16249   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16250           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16251          "Invalid Frame Register!");
16252   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16253   while (Depth--)
16254     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16255                             MachinePointerInfo(),
16256                             false, false, false, 0);
16257   return FrameAddr;
16258 }
16259
16260 // FIXME? Maybe this could be a TableGen attribute on some registers and
16261 // this table could be generated automatically from RegInfo.
16262 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
16263                                               EVT VT) const {
16264   unsigned Reg = StringSwitch<unsigned>(RegName)
16265                        .Case("esp", X86::ESP)
16266                        .Case("rsp", X86::RSP)
16267                        .Default(0);
16268   if (Reg)
16269     return Reg;
16270   report_fatal_error("Invalid register name global variable");
16271 }
16272
16273 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16274                                                      SelectionDAG &DAG) const {
16275   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16276   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16277 }
16278
16279 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16280   SDValue Chain     = Op.getOperand(0);
16281   SDValue Offset    = Op.getOperand(1);
16282   SDValue Handler   = Op.getOperand(2);
16283   SDLoc dl      (Op);
16284
16285   EVT PtrVT = getPointerTy();
16286   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16287   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16288   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16289           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16290          "Invalid Frame Register!");
16291   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16292   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16293
16294   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16295                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16296                                                        dl));
16297   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16298   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16299                        false, false, 0);
16300   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16301
16302   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16303                      DAG.getRegister(StoreAddrReg, PtrVT));
16304 }
16305
16306 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16307                                                SelectionDAG &DAG) const {
16308   SDLoc DL(Op);
16309   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16310                      DAG.getVTList(MVT::i32, MVT::Other),
16311                      Op.getOperand(0), Op.getOperand(1));
16312 }
16313
16314 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16315                                                 SelectionDAG &DAG) const {
16316   SDLoc DL(Op);
16317   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16318                      Op.getOperand(0), Op.getOperand(1));
16319 }
16320
16321 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16322   return Op.getOperand(0);
16323 }
16324
16325 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16326                                                 SelectionDAG &DAG) const {
16327   SDValue Root = Op.getOperand(0);
16328   SDValue Trmp = Op.getOperand(1); // trampoline
16329   SDValue FPtr = Op.getOperand(2); // nested function
16330   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16331   SDLoc dl (Op);
16332
16333   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16334   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16335
16336   if (Subtarget->is64Bit()) {
16337     SDValue OutChains[6];
16338
16339     // Large code-model.
16340     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16341     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16342
16343     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16344     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16345
16346     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16347
16348     // Load the pointer to the nested function into R11.
16349     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16350     SDValue Addr = Trmp;
16351     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16352                                 Addr, MachinePointerInfo(TrmpAddr),
16353                                 false, false, 0);
16354
16355     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16356                        DAG.getConstant(2, dl, MVT::i64));
16357     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16358                                 MachinePointerInfo(TrmpAddr, 2),
16359                                 false, false, 2);
16360
16361     // Load the 'nest' parameter value into R10.
16362     // R10 is specified in X86CallingConv.td
16363     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16364     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16365                        DAG.getConstant(10, dl, MVT::i64));
16366     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16367                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16368                                 false, false, 0);
16369
16370     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16371                        DAG.getConstant(12, dl, MVT::i64));
16372     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16373                                 MachinePointerInfo(TrmpAddr, 12),
16374                                 false, false, 2);
16375
16376     // Jump to the nested function.
16377     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16378     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16379                        DAG.getConstant(20, dl, MVT::i64));
16380     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16381                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16382                                 false, false, 0);
16383
16384     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16385     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16386                        DAG.getConstant(22, dl, MVT::i64));
16387     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16388                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16389                                 false, false, 0);
16390
16391     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16392   } else {
16393     const Function *Func =
16394       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16395     CallingConv::ID CC = Func->getCallingConv();
16396     unsigned NestReg;
16397
16398     switch (CC) {
16399     default:
16400       llvm_unreachable("Unsupported calling convention");
16401     case CallingConv::C:
16402     case CallingConv::X86_StdCall: {
16403       // Pass 'nest' parameter in ECX.
16404       // Must be kept in sync with X86CallingConv.td
16405       NestReg = X86::ECX;
16406
16407       // Check that ECX wasn't needed by an 'inreg' parameter.
16408       FunctionType *FTy = Func->getFunctionType();
16409       const AttributeSet &Attrs = Func->getAttributes();
16410
16411       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16412         unsigned InRegCount = 0;
16413         unsigned Idx = 1;
16414
16415         for (FunctionType::param_iterator I = FTy->param_begin(),
16416              E = FTy->param_end(); I != E; ++I, ++Idx)
16417           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16418             // FIXME: should only count parameters that are lowered to integers.
16419             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16420
16421         if (InRegCount > 2) {
16422           report_fatal_error("Nest register in use - reduce number of inreg"
16423                              " parameters!");
16424         }
16425       }
16426       break;
16427     }
16428     case CallingConv::X86_FastCall:
16429     case CallingConv::X86_ThisCall:
16430     case CallingConv::Fast:
16431       // Pass 'nest' parameter in EAX.
16432       // Must be kept in sync with X86CallingConv.td
16433       NestReg = X86::EAX;
16434       break;
16435     }
16436
16437     SDValue OutChains[4];
16438     SDValue Addr, Disp;
16439
16440     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16441                        DAG.getConstant(10, dl, MVT::i32));
16442     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16443
16444     // This is storing the opcode for MOV32ri.
16445     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16446     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16447     OutChains[0] = DAG.getStore(Root, dl,
16448                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16449                                 Trmp, MachinePointerInfo(TrmpAddr),
16450                                 false, false, 0);
16451
16452     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16453                        DAG.getConstant(1, dl, MVT::i32));
16454     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16455                                 MachinePointerInfo(TrmpAddr, 1),
16456                                 false, false, 1);
16457
16458     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16459     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16460                        DAG.getConstant(5, dl, MVT::i32));
16461     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16462                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16463                                 false, false, 1);
16464
16465     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16466                        DAG.getConstant(6, dl, MVT::i32));
16467     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16468                                 MachinePointerInfo(TrmpAddr, 6),
16469                                 false, false, 1);
16470
16471     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16472   }
16473 }
16474
16475 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16476                                             SelectionDAG &DAG) const {
16477   /*
16478    The rounding mode is in bits 11:10 of FPSR, and has the following
16479    settings:
16480      00 Round to nearest
16481      01 Round to -inf
16482      10 Round to +inf
16483      11 Round to 0
16484
16485   FLT_ROUNDS, on the other hand, expects the following:
16486     -1 Undefined
16487      0 Round to 0
16488      1 Round to nearest
16489      2 Round to +inf
16490      3 Round to -inf
16491
16492   To perform the conversion, we do:
16493     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16494   */
16495
16496   MachineFunction &MF = DAG.getMachineFunction();
16497   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16498   unsigned StackAlignment = TFI.getStackAlignment();
16499   MVT VT = Op.getSimpleValueType();
16500   SDLoc DL(Op);
16501
16502   // Save FP Control Word to stack slot
16503   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16504   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16505
16506   MachineMemOperand *MMO =
16507    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16508                            MachineMemOperand::MOStore, 2, 2);
16509
16510   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16511   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16512                                           DAG.getVTList(MVT::Other),
16513                                           Ops, MVT::i16, MMO);
16514
16515   // Load FP Control Word from stack slot
16516   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16517                             MachinePointerInfo(), false, false, false, 0);
16518
16519   // Transform as necessary
16520   SDValue CWD1 =
16521     DAG.getNode(ISD::SRL, DL, MVT::i16,
16522                 DAG.getNode(ISD::AND, DL, MVT::i16,
16523                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16524                 DAG.getConstant(11, DL, MVT::i8));
16525   SDValue CWD2 =
16526     DAG.getNode(ISD::SRL, DL, MVT::i16,
16527                 DAG.getNode(ISD::AND, DL, MVT::i16,
16528                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16529                 DAG.getConstant(9, DL, MVT::i8));
16530
16531   SDValue RetVal =
16532     DAG.getNode(ISD::AND, DL, MVT::i16,
16533                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16534                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16535                             DAG.getConstant(1, DL, MVT::i16)),
16536                 DAG.getConstant(3, DL, MVT::i16));
16537
16538   return DAG.getNode((VT.getSizeInBits() < 16 ?
16539                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16540 }
16541
16542 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16543   MVT VT = Op.getSimpleValueType();
16544   EVT OpVT = VT;
16545   unsigned NumBits = VT.getSizeInBits();
16546   SDLoc dl(Op);
16547
16548   Op = Op.getOperand(0);
16549   if (VT == MVT::i8) {
16550     // Zero extend to i32 since there is not an i8 bsr.
16551     OpVT = MVT::i32;
16552     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16553   }
16554
16555   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16556   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16557   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16558
16559   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16560   SDValue Ops[] = {
16561     Op,
16562     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16563     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16564     Op.getValue(1)
16565   };
16566   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16567
16568   // Finally xor with NumBits-1.
16569   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16570                    DAG.getConstant(NumBits - 1, dl, OpVT));
16571
16572   if (VT == MVT::i8)
16573     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16574   return Op;
16575 }
16576
16577 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16578   MVT VT = Op.getSimpleValueType();
16579   EVT OpVT = VT;
16580   unsigned NumBits = VT.getSizeInBits();
16581   SDLoc dl(Op);
16582
16583   Op = Op.getOperand(0);
16584   if (VT == MVT::i8) {
16585     // Zero extend to i32 since there is not an i8 bsr.
16586     OpVT = MVT::i32;
16587     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16588   }
16589
16590   // Issue a bsr (scan bits in reverse).
16591   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16592   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16593
16594   // And xor with NumBits-1.
16595   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16596                    DAG.getConstant(NumBits - 1, dl, OpVT));
16597
16598   if (VT == MVT::i8)
16599     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16600   return Op;
16601 }
16602
16603 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16604   MVT VT = Op.getSimpleValueType();
16605   unsigned NumBits = VT.getSizeInBits();
16606   SDLoc dl(Op);
16607   Op = Op.getOperand(0);
16608
16609   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16610   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16611   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16612
16613   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16614   SDValue Ops[] = {
16615     Op,
16616     DAG.getConstant(NumBits, dl, VT),
16617     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16618     Op.getValue(1)
16619   };
16620   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16621 }
16622
16623 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16624 // ones, and then concatenate the result back.
16625 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16626   MVT VT = Op.getSimpleValueType();
16627
16628   assert(VT.is256BitVector() && VT.isInteger() &&
16629          "Unsupported value type for operation");
16630
16631   unsigned NumElems = VT.getVectorNumElements();
16632   SDLoc dl(Op);
16633
16634   // Extract the LHS vectors
16635   SDValue LHS = Op.getOperand(0);
16636   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16637   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16638
16639   // Extract the RHS vectors
16640   SDValue RHS = Op.getOperand(1);
16641   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16642   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16643
16644   MVT EltVT = VT.getVectorElementType();
16645   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16646
16647   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16648                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16649                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16650 }
16651
16652 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16653   if (Op.getValueType() == MVT::i1)
16654     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16655                        Op.getOperand(0), Op.getOperand(1));
16656   assert(Op.getSimpleValueType().is256BitVector() &&
16657          Op.getSimpleValueType().isInteger() &&
16658          "Only handle AVX 256-bit vector integer operation");
16659   return Lower256IntArith(Op, DAG);
16660 }
16661
16662 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16663   if (Op.getValueType() == MVT::i1)
16664     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16665                        Op.getOperand(0), Op.getOperand(1));
16666   assert(Op.getSimpleValueType().is256BitVector() &&
16667          Op.getSimpleValueType().isInteger() &&
16668          "Only handle AVX 256-bit vector integer operation");
16669   return Lower256IntArith(Op, DAG);
16670 }
16671
16672 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16673                         SelectionDAG &DAG) {
16674   SDLoc dl(Op);
16675   MVT VT = Op.getSimpleValueType();
16676
16677   if (VT == MVT::i1)
16678     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16679
16680   // Decompose 256-bit ops into smaller 128-bit ops.
16681   if (VT.is256BitVector() && !Subtarget->hasInt256())
16682     return Lower256IntArith(Op, DAG);
16683
16684   SDValue A = Op.getOperand(0);
16685   SDValue B = Op.getOperand(1);
16686
16687   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16688   // pairs, multiply and truncate.
16689   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16690     if (Subtarget->hasInt256()) {
16691       if (VT == MVT::v32i8) {
16692         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16693         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16694         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16695         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16696         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16697         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16698         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16699         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16700                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16701                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16702       }
16703
16704       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16705       return DAG.getNode(
16706           ISD::TRUNCATE, dl, VT,
16707           DAG.getNode(ISD::MUL, dl, ExVT,
16708                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16709                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16710     }
16711
16712     assert(VT == MVT::v16i8 &&
16713            "Pre-AVX2 support only supports v16i8 multiplication");
16714     MVT ExVT = MVT::v8i16;
16715
16716     // Extract the lo parts and sign extend to i16
16717     SDValue ALo, BLo;
16718     if (Subtarget->hasSSE41()) {
16719       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16720       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16721     } else {
16722       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16723                               -1, 4, -1, 5, -1, 6, -1, 7};
16724       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16725       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16726       ALo = DAG.getBitcast(ExVT, ALo);
16727       BLo = DAG.getBitcast(ExVT, BLo);
16728       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16729       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16730     }
16731
16732     // Extract the hi parts and sign extend to i16
16733     SDValue AHi, BHi;
16734     if (Subtarget->hasSSE41()) {
16735       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16736                               -1, -1, -1, -1, -1, -1, -1, -1};
16737       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16738       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16739       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16740       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16741     } else {
16742       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16743                               -1, 12, -1, 13, -1, 14, -1, 15};
16744       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16745       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16746       AHi = DAG.getBitcast(ExVT, AHi);
16747       BHi = DAG.getBitcast(ExVT, BHi);
16748       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16749       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16750     }
16751
16752     // Multiply, mask the lower 8bits of the lo/hi results and pack
16753     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16754     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16755     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16756     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16757     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16758   }
16759
16760   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16761   if (VT == MVT::v4i32) {
16762     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16763            "Should not custom lower when pmuldq is available!");
16764
16765     // Extract the odd parts.
16766     static const int UnpackMask[] = { 1, -1, 3, -1 };
16767     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16768     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16769
16770     // Multiply the even parts.
16771     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16772     // Now multiply odd parts.
16773     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16774
16775     Evens = DAG.getBitcast(VT, Evens);
16776     Odds = DAG.getBitcast(VT, Odds);
16777
16778     // Merge the two vectors back together with a shuffle. This expands into 2
16779     // shuffles.
16780     static const int ShufMask[] = { 0, 4, 2, 6 };
16781     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16782   }
16783
16784   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16785          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16786
16787   //  Ahi = psrlqi(a, 32);
16788   //  Bhi = psrlqi(b, 32);
16789   //
16790   //  AloBlo = pmuludq(a, b);
16791   //  AloBhi = pmuludq(a, Bhi);
16792   //  AhiBlo = pmuludq(Ahi, b);
16793
16794   //  AloBhi = psllqi(AloBhi, 32);
16795   //  AhiBlo = psllqi(AhiBlo, 32);
16796   //  return AloBlo + AloBhi + AhiBlo;
16797
16798   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16799   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16800
16801   SDValue AhiBlo = Ahi;
16802   SDValue AloBhi = Bhi;
16803   // Bit cast to 32-bit vectors for MULUDQ
16804   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16805                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16806   A = DAG.getBitcast(MulVT, A);
16807   B = DAG.getBitcast(MulVT, B);
16808   Ahi = DAG.getBitcast(MulVT, Ahi);
16809   Bhi = DAG.getBitcast(MulVT, Bhi);
16810
16811   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16812   // After shifting right const values the result may be all-zero.
16813   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16814     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16815     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16816   }
16817   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16818     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16819     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16820   }
16821
16822   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16823   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16824 }
16825
16826 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16827   assert(Subtarget->isTargetWin64() && "Unexpected target");
16828   EVT VT = Op.getValueType();
16829   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16830          "Unexpected return type for lowering");
16831
16832   RTLIB::Libcall LC;
16833   bool isSigned;
16834   switch (Op->getOpcode()) {
16835   default: llvm_unreachable("Unexpected request for libcall!");
16836   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16837   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16838   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16839   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16840   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16841   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16842   }
16843
16844   SDLoc dl(Op);
16845   SDValue InChain = DAG.getEntryNode();
16846
16847   TargetLowering::ArgListTy Args;
16848   TargetLowering::ArgListEntry Entry;
16849   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16850     EVT ArgVT = Op->getOperand(i).getValueType();
16851     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16852            "Unexpected argument type for lowering");
16853     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16854     Entry.Node = StackPtr;
16855     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16856                            false, false, 16);
16857     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16858     Entry.Ty = PointerType::get(ArgTy,0);
16859     Entry.isSExt = false;
16860     Entry.isZExt = false;
16861     Args.push_back(Entry);
16862   }
16863
16864   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16865                                          getPointerTy());
16866
16867   TargetLowering::CallLoweringInfo CLI(DAG);
16868   CLI.setDebugLoc(dl).setChain(InChain)
16869     .setCallee(getLibcallCallingConv(LC),
16870                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16871                Callee, std::move(Args), 0)
16872     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16873
16874   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16875   return DAG.getBitcast(VT, CallInfo.first);
16876 }
16877
16878 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16879                              SelectionDAG &DAG) {
16880   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16881   EVT VT = Op0.getValueType();
16882   SDLoc dl(Op);
16883
16884   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16885          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16886
16887   // PMULxD operations multiply each even value (starting at 0) of LHS with
16888   // the related value of RHS and produce a widen result.
16889   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16890   // => <2 x i64> <ae|cg>
16891   //
16892   // In other word, to have all the results, we need to perform two PMULxD:
16893   // 1. one with the even values.
16894   // 2. one with the odd values.
16895   // To achieve #2, with need to place the odd values at an even position.
16896   //
16897   // Place the odd value at an even position (basically, shift all values 1
16898   // step to the left):
16899   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16900   // <a|b|c|d> => <b|undef|d|undef>
16901   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16902   // <e|f|g|h> => <f|undef|h|undef>
16903   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16904
16905   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16906   // ints.
16907   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16908   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16909   unsigned Opcode =
16910       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16911   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16912   // => <2 x i64> <ae|cg>
16913   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16914   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16915   // => <2 x i64> <bf|dh>
16916   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16917
16918   // Shuffle it back into the right order.
16919   SDValue Highs, Lows;
16920   if (VT == MVT::v8i32) {
16921     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16922     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16923     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16924     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16925   } else {
16926     const int HighMask[] = {1, 5, 3, 7};
16927     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16928     const int LowMask[] = {0, 4, 2, 6};
16929     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16930   }
16931
16932   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16933   // unsigned multiply.
16934   if (IsSigned && !Subtarget->hasSSE41()) {
16935     SDValue ShAmt =
16936         DAG.getConstant(31, dl,
16937                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16938     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16939                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16940     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16941                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16942
16943     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16944     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16945   }
16946
16947   // The first result of MUL_LOHI is actually the low value, followed by the
16948   // high value.
16949   SDValue Ops[] = {Lows, Highs};
16950   return DAG.getMergeValues(Ops, dl);
16951 }
16952
16953 // Return true if the requred (according to Opcode) shift-imm form is natively
16954 // supported by the Subtarget
16955 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16956                                         unsigned Opcode) {
16957   if (VT.getScalarSizeInBits() < 16)
16958     return false;
16959
16960   if (VT.is512BitVector() &&
16961       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16962     return true;
16963
16964   bool LShift = VT.is128BitVector() ||
16965     (VT.is256BitVector() && Subtarget->hasInt256());
16966
16967   bool AShift = LShift && (Subtarget->hasVLX() ||
16968     (VT != MVT::v2i64 && VT != MVT::v4i64));
16969   return (Opcode == ISD::SRA) ? AShift : LShift;
16970 }
16971
16972 // The shift amount is a variable, but it is the same for all vector lanes.
16973 // These instrcutions are defined together with shift-immediate.
16974 static
16975 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
16976                                       unsigned Opcode) {
16977   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16978 }
16979
16980 // Return true if the requred (according to Opcode) variable-shift form is
16981 // natively supported by the Subtarget
16982 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
16983                                     unsigned Opcode) {
16984
16985   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16986     return false;
16987
16988   // vXi16 supported only on AVX-512, BWI
16989   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16990     return false;
16991
16992   if (VT.is512BitVector() || Subtarget->hasVLX())
16993     return true;
16994
16995   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16996   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16997   return (Opcode == ISD::SRA) ? AShift : LShift;
16998 }
16999
17000 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17001                                          const X86Subtarget *Subtarget) {
17002   MVT VT = Op.getSimpleValueType();
17003   SDLoc dl(Op);
17004   SDValue R = Op.getOperand(0);
17005   SDValue Amt = Op.getOperand(1);
17006
17007   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17008     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17009
17010   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17011     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17012     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17013     SDValue Ex = DAG.getBitcast(ExVT, R);
17014
17015     if (ShiftAmt >= 32) {
17016       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17017       SDValue Upper =
17018           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17019       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17020                                                  ShiftAmt - 32, DAG);
17021       if (VT == MVT::v2i64)
17022         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17023       if (VT == MVT::v4i64)
17024         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17025                                   {9, 1, 11, 3, 13, 5, 15, 7});
17026     } else {
17027       // SRA upper i32, SHL whole i64 and select lower i32.
17028       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17029                                                  ShiftAmt, DAG);
17030       SDValue Lower =
17031           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17032       Lower = DAG.getBitcast(ExVT, Lower);
17033       if (VT == MVT::v2i64)
17034         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17035       if (VT == MVT::v4i64)
17036         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17037                                   {8, 1, 10, 3, 12, 5, 14, 7});
17038     }
17039     return DAG.getBitcast(VT, Ex);
17040   };
17041
17042   // Optimize shl/srl/sra with constant shift amount.
17043   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17044     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17045       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17046
17047       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17048         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17049
17050       // i64 SRA needs to be performed as partial shifts.
17051       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17052           Op.getOpcode() == ISD::SRA)
17053         return ArithmeticShiftRight64(ShiftAmt);
17054
17055       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17056         unsigned NumElts = VT.getVectorNumElements();
17057         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17058
17059         if (Op.getOpcode() == ISD::SHL) {
17060           // Simple i8 add case
17061           if (ShiftAmt == 1)
17062             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17063
17064           // Make a large shift.
17065           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17066                                                    R, ShiftAmt, DAG);
17067           SHL = DAG.getBitcast(VT, SHL);
17068           // Zero out the rightmost bits.
17069           SmallVector<SDValue, 32> V(
17070               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17071           return DAG.getNode(ISD::AND, dl, VT, SHL,
17072                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17073         }
17074         if (Op.getOpcode() == ISD::SRL) {
17075           // Make a large shift.
17076           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17077                                                    R, ShiftAmt, DAG);
17078           SRL = DAG.getBitcast(VT, SRL);
17079           // Zero out the leftmost bits.
17080           SmallVector<SDValue, 32> V(
17081               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17082           return DAG.getNode(ISD::AND, dl, VT, SRL,
17083                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17084         }
17085         if (Op.getOpcode() == ISD::SRA) {
17086           if (ShiftAmt == 7) {
17087             // R s>> 7  ===  R s< 0
17088             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17089             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17090           }
17091
17092           // R s>> a === ((R u>> a) ^ m) - m
17093           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17094           SmallVector<SDValue, 32> V(NumElts,
17095                                      DAG.getConstant(128 >> ShiftAmt, dl,
17096                                                      MVT::i8));
17097           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17098           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17099           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17100           return Res;
17101         }
17102         llvm_unreachable("Unknown shift opcode.");
17103       }
17104     }
17105   }
17106
17107   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17108   if (!Subtarget->is64Bit() &&
17109       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17110       Amt.getOpcode() == ISD::BITCAST &&
17111       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17112     Amt = Amt.getOperand(0);
17113     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17114                      VT.getVectorNumElements();
17115     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17116     uint64_t ShiftAmt = 0;
17117     for (unsigned i = 0; i != Ratio; ++i) {
17118       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17119       if (!C)
17120         return SDValue();
17121       // 6 == Log2(64)
17122       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17123     }
17124     // Check remaining shift amounts.
17125     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17126       uint64_t ShAmt = 0;
17127       for (unsigned j = 0; j != Ratio; ++j) {
17128         ConstantSDNode *C =
17129           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17130         if (!C)
17131           return SDValue();
17132         // 6 == Log2(64)
17133         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17134       }
17135       if (ShAmt != ShiftAmt)
17136         return SDValue();
17137     }
17138
17139     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17140       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17141
17142     if (Op.getOpcode() == ISD::SRA)
17143       return ArithmeticShiftRight64(ShiftAmt);
17144   }
17145
17146   return SDValue();
17147 }
17148
17149 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17150                                         const X86Subtarget* Subtarget) {
17151   MVT VT = Op.getSimpleValueType();
17152   SDLoc dl(Op);
17153   SDValue R = Op.getOperand(0);
17154   SDValue Amt = Op.getOperand(1);
17155
17156   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17157     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17158
17159   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17160     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17161
17162   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17163     SDValue BaseShAmt;
17164     EVT EltVT = VT.getVectorElementType();
17165
17166     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17167       // Check if this build_vector node is doing a splat.
17168       // If so, then set BaseShAmt equal to the splat value.
17169       BaseShAmt = BV->getSplatValue();
17170       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17171         BaseShAmt = SDValue();
17172     } else {
17173       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17174         Amt = Amt.getOperand(0);
17175
17176       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17177       if (SVN && SVN->isSplat()) {
17178         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17179         SDValue InVec = Amt.getOperand(0);
17180         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17181           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17182                  "Unexpected shuffle index found!");
17183           BaseShAmt = InVec.getOperand(SplatIdx);
17184         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17185            if (ConstantSDNode *C =
17186                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17187              if (C->getZExtValue() == SplatIdx)
17188                BaseShAmt = InVec.getOperand(1);
17189            }
17190         }
17191
17192         if (!BaseShAmt)
17193           // Avoid introducing an extract element from a shuffle.
17194           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17195                                   DAG.getIntPtrConstant(SplatIdx, dl));
17196       }
17197     }
17198
17199     if (BaseShAmt.getNode()) {
17200       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17201       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17202         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17203       else if (EltVT.bitsLT(MVT::i32))
17204         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17205
17206       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17207     }
17208   }
17209
17210   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17211   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17212       Amt.getOpcode() == ISD::BITCAST &&
17213       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17214     Amt = Amt.getOperand(0);
17215     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17216                      VT.getVectorNumElements();
17217     std::vector<SDValue> Vals(Ratio);
17218     for (unsigned i = 0; i != Ratio; ++i)
17219       Vals[i] = Amt.getOperand(i);
17220     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17221       for (unsigned j = 0; j != Ratio; ++j)
17222         if (Vals[j] != Amt.getOperand(i + j))
17223           return SDValue();
17224     }
17225
17226     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17227       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17228   }
17229   return SDValue();
17230 }
17231
17232 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17233                           SelectionDAG &DAG) {
17234   MVT VT = Op.getSimpleValueType();
17235   SDLoc dl(Op);
17236   SDValue R = Op.getOperand(0);
17237   SDValue Amt = Op.getOperand(1);
17238
17239   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17240   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17241
17242   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17243     return V;
17244
17245   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17246       return V;
17247
17248   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17249     return Op;
17250
17251   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17252   // shifts per-lane and then shuffle the partial results back together.
17253   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17254     // Splat the shift amounts so the scalar shifts above will catch it.
17255     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17256     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17257     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17258     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17259     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17260   }
17261
17262   // If possible, lower this packed shift into a vector multiply instead of
17263   // expanding it into a sequence of scalar shifts.
17264   // Do this only if the vector shift count is a constant build_vector.
17265   if (Op.getOpcode() == ISD::SHL &&
17266       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17267        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17268       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17269     SmallVector<SDValue, 8> Elts;
17270     EVT SVT = VT.getScalarType();
17271     unsigned SVTBits = SVT.getSizeInBits();
17272     const APInt &One = APInt(SVTBits, 1);
17273     unsigned NumElems = VT.getVectorNumElements();
17274
17275     for (unsigned i=0; i !=NumElems; ++i) {
17276       SDValue Op = Amt->getOperand(i);
17277       if (Op->getOpcode() == ISD::UNDEF) {
17278         Elts.push_back(Op);
17279         continue;
17280       }
17281
17282       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17283       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17284       uint64_t ShAmt = C.getZExtValue();
17285       if (ShAmt >= SVTBits) {
17286         Elts.push_back(DAG.getUNDEF(SVT));
17287         continue;
17288       }
17289       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17290     }
17291     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17292     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17293   }
17294
17295   // Lower SHL with variable shift amount.
17296   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17297     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17298
17299     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17300                      DAG.getConstant(0x3f800000U, dl, VT));
17301     Op = DAG.getBitcast(MVT::v4f32, Op);
17302     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17303     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17304   }
17305
17306   // If possible, lower this shift as a sequence of two shifts by
17307   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17308   // Example:
17309   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17310   //
17311   // Could be rewritten as:
17312   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17313   //
17314   // The advantage is that the two shifts from the example would be
17315   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17316   // the vector shift into four scalar shifts plus four pairs of vector
17317   // insert/extract.
17318   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17319       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17320     unsigned TargetOpcode = X86ISD::MOVSS;
17321     bool CanBeSimplified;
17322     // The splat value for the first packed shift (the 'X' from the example).
17323     SDValue Amt1 = Amt->getOperand(0);
17324     // The splat value for the second packed shift (the 'Y' from the example).
17325     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17326                                         Amt->getOperand(2);
17327
17328     // See if it is possible to replace this node with a sequence of
17329     // two shifts followed by a MOVSS/MOVSD
17330     if (VT == MVT::v4i32) {
17331       // Check if it is legal to use a MOVSS.
17332       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17333                         Amt2 == Amt->getOperand(3);
17334       if (!CanBeSimplified) {
17335         // Otherwise, check if we can still simplify this node using a MOVSD.
17336         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17337                           Amt->getOperand(2) == Amt->getOperand(3);
17338         TargetOpcode = X86ISD::MOVSD;
17339         Amt2 = Amt->getOperand(2);
17340       }
17341     } else {
17342       // Do similar checks for the case where the machine value type
17343       // is MVT::v8i16.
17344       CanBeSimplified = Amt1 == Amt->getOperand(1);
17345       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17346         CanBeSimplified = Amt2 == Amt->getOperand(i);
17347
17348       if (!CanBeSimplified) {
17349         TargetOpcode = X86ISD::MOVSD;
17350         CanBeSimplified = true;
17351         Amt2 = Amt->getOperand(4);
17352         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17353           CanBeSimplified = Amt1 == Amt->getOperand(i);
17354         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17355           CanBeSimplified = Amt2 == Amt->getOperand(j);
17356       }
17357     }
17358
17359     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17360         isa<ConstantSDNode>(Amt2)) {
17361       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17362       EVT CastVT = MVT::v4i32;
17363       SDValue Splat1 =
17364         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17365       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17366       SDValue Splat2 =
17367         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17368       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17369       if (TargetOpcode == X86ISD::MOVSD)
17370         CastVT = MVT::v2i64;
17371       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17372       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17373       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17374                                             BitCast1, DAG);
17375       return DAG.getBitcast(VT, Result);
17376     }
17377   }
17378
17379   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17380     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17381     unsigned ShiftOpcode = Op->getOpcode();
17382
17383     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17384       // On SSE41 targets we make use of the fact that VSELECT lowers
17385       // to PBLENDVB which selects bytes based just on the sign bit.
17386       if (Subtarget->hasSSE41()) {
17387         V0 = DAG.getBitcast(VT, V0);
17388         V1 = DAG.getBitcast(VT, V1);
17389         Sel = DAG.getBitcast(VT, Sel);
17390         return DAG.getBitcast(SelVT,
17391                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17392       }
17393       // On pre-SSE41 targets we test for the sign bit by comparing to
17394       // zero - a negative value will set all bits of the lanes to true
17395       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17396       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17397       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17398       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17399     };
17400
17401     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17402     // We can safely do this using i16 shifts as we're only interested in
17403     // the 3 lower bits of each byte.
17404     Amt = DAG.getBitcast(ExtVT, Amt);
17405     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17406     Amt = DAG.getBitcast(VT, Amt);
17407
17408     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17409       // r = VSELECT(r, shift(r, 4), a);
17410       SDValue M =
17411           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17412       R = SignBitSelect(VT, Amt, M, R);
17413
17414       // a += a
17415       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17416
17417       // r = VSELECT(r, shift(r, 2), a);
17418       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17419       R = SignBitSelect(VT, Amt, M, R);
17420
17421       // a += a
17422       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17423
17424       // return VSELECT(r, shift(r, 1), a);
17425       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17426       R = SignBitSelect(VT, Amt, M, R);
17427       return R;
17428     }
17429
17430     if (Op->getOpcode() == ISD::SRA) {
17431       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17432       // so we can correctly sign extend. We don't care what happens to the
17433       // lower byte.
17434       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17435       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17436       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17437       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17438       ALo = DAG.getBitcast(ExtVT, ALo);
17439       AHi = DAG.getBitcast(ExtVT, AHi);
17440       RLo = DAG.getBitcast(ExtVT, RLo);
17441       RHi = DAG.getBitcast(ExtVT, RHi);
17442
17443       // r = VSELECT(r, shift(r, 4), a);
17444       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17445                                 DAG.getConstant(4, dl, ExtVT));
17446       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17447                                 DAG.getConstant(4, dl, ExtVT));
17448       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17449       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17450
17451       // a += a
17452       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17453       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17454
17455       // r = VSELECT(r, shift(r, 2), a);
17456       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17457                         DAG.getConstant(2, dl, ExtVT));
17458       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17459                         DAG.getConstant(2, dl, ExtVT));
17460       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17461       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17462
17463       // a += a
17464       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17465       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17466
17467       // r = VSELECT(r, shift(r, 1), a);
17468       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17469                         DAG.getConstant(1, dl, ExtVT));
17470       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17471                         DAG.getConstant(1, dl, ExtVT));
17472       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17473       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17474
17475       // Logical shift the result back to the lower byte, leaving a zero upper
17476       // byte
17477       // meaning that we can safely pack with PACKUSWB.
17478       RLo =
17479           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17480       RHi =
17481           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17482       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17483     }
17484   }
17485
17486   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17487   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17488   // solution better.
17489   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17490     MVT ExtVT = MVT::v8i32;
17491     unsigned ExtOpc =
17492         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17493     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17494     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17495     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17496                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17497   }
17498
17499   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17500     MVT ExtVT = MVT::v8i32;
17501     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17502     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17503     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17504     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17505     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17506     ALo = DAG.getBitcast(ExtVT, ALo);
17507     AHi = DAG.getBitcast(ExtVT, AHi);
17508     RLo = DAG.getBitcast(ExtVT, RLo);
17509     RHi = DAG.getBitcast(ExtVT, RHi);
17510     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17511     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17512     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17513     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17514     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17515   }
17516
17517   if (VT == MVT::v8i16) {
17518     unsigned ShiftOpcode = Op->getOpcode();
17519
17520     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17521       // On SSE41 targets we make use of the fact that VSELECT lowers
17522       // to PBLENDVB which selects bytes based just on the sign bit.
17523       if (Subtarget->hasSSE41()) {
17524         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17525         V0 = DAG.getBitcast(ExtVT, V0);
17526         V1 = DAG.getBitcast(ExtVT, V1);
17527         Sel = DAG.getBitcast(ExtVT, Sel);
17528         return DAG.getBitcast(
17529             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17530       }
17531       // On pre-SSE41 targets we splat the sign bit - a negative value will
17532       // set all bits of the lanes to true and VSELECT uses that in
17533       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17534       SDValue C =
17535           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17536       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17537     };
17538
17539     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17540     if (Subtarget->hasSSE41()) {
17541       // On SSE41 targets we need to replicate the shift mask in both
17542       // bytes for PBLENDVB.
17543       Amt = DAG.getNode(
17544           ISD::OR, dl, VT,
17545           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17546           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17547     } else {
17548       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17549     }
17550
17551     // r = VSELECT(r, shift(r, 8), a);
17552     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17553     R = SignBitSelect(Amt, M, R);
17554
17555     // a += a
17556     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17557
17558     // r = VSELECT(r, shift(r, 4), a);
17559     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17560     R = SignBitSelect(Amt, M, R);
17561
17562     // a += a
17563     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17564
17565     // r = VSELECT(r, shift(r, 2), a);
17566     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17567     R = SignBitSelect(Amt, M, R);
17568
17569     // a += a
17570     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17571
17572     // return VSELECT(r, shift(r, 1), a);
17573     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17574     R = SignBitSelect(Amt, M, R);
17575     return R;
17576   }
17577
17578   // Decompose 256-bit shifts into smaller 128-bit shifts.
17579   if (VT.is256BitVector()) {
17580     unsigned NumElems = VT.getVectorNumElements();
17581     MVT EltVT = VT.getVectorElementType();
17582     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17583
17584     // Extract the two vectors
17585     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17586     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17587
17588     // Recreate the shift amount vectors
17589     SDValue Amt1, Amt2;
17590     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17591       // Constant shift amount
17592       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17593       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17594       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17595
17596       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17597       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17598     } else {
17599       // Variable shift amount
17600       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17601       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17602     }
17603
17604     // Issue new vector shifts for the smaller types
17605     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17606     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17607
17608     // Concatenate the result back
17609     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17610   }
17611
17612   return SDValue();
17613 }
17614
17615 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17616   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17617   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17618   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17619   // has only one use.
17620   SDNode *N = Op.getNode();
17621   SDValue LHS = N->getOperand(0);
17622   SDValue RHS = N->getOperand(1);
17623   unsigned BaseOp = 0;
17624   unsigned Cond = 0;
17625   SDLoc DL(Op);
17626   switch (Op.getOpcode()) {
17627   default: llvm_unreachable("Unknown ovf instruction!");
17628   case ISD::SADDO:
17629     // A subtract of one will be selected as a INC. Note that INC doesn't
17630     // set CF, so we can't do this for UADDO.
17631     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17632       if (C->isOne()) {
17633         BaseOp = X86ISD::INC;
17634         Cond = X86::COND_O;
17635         break;
17636       }
17637     BaseOp = X86ISD::ADD;
17638     Cond = X86::COND_O;
17639     break;
17640   case ISD::UADDO:
17641     BaseOp = X86ISD::ADD;
17642     Cond = X86::COND_B;
17643     break;
17644   case ISD::SSUBO:
17645     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17646     // set CF, so we can't do this for USUBO.
17647     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17648       if (C->isOne()) {
17649         BaseOp = X86ISD::DEC;
17650         Cond = X86::COND_O;
17651         break;
17652       }
17653     BaseOp = X86ISD::SUB;
17654     Cond = X86::COND_O;
17655     break;
17656   case ISD::USUBO:
17657     BaseOp = X86ISD::SUB;
17658     Cond = X86::COND_B;
17659     break;
17660   case ISD::SMULO:
17661     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17662     Cond = X86::COND_O;
17663     break;
17664   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17665     if (N->getValueType(0) == MVT::i8) {
17666       BaseOp = X86ISD::UMUL8;
17667       Cond = X86::COND_O;
17668       break;
17669     }
17670     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17671                                  MVT::i32);
17672     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17673
17674     SDValue SetCC =
17675       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17676                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17677                   SDValue(Sum.getNode(), 2));
17678
17679     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17680   }
17681   }
17682
17683   // Also sets EFLAGS.
17684   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17685   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17686
17687   SDValue SetCC =
17688     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17689                 DAG.getConstant(Cond, DL, MVT::i32),
17690                 SDValue(Sum.getNode(), 1));
17691
17692   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17693 }
17694
17695 /// Returns true if the operand type is exactly twice the native width, and
17696 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17697 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17698 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17699 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17700   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17701
17702   if (OpWidth == 64)
17703     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17704   else if (OpWidth == 128)
17705     return Subtarget->hasCmpxchg16b();
17706   else
17707     return false;
17708 }
17709
17710 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17711   return needsCmpXchgNb(SI->getValueOperand()->getType());
17712 }
17713
17714 // Note: this turns large loads into lock cmpxchg8b/16b.
17715 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17716 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17717   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17718   return needsCmpXchgNb(PTy->getElementType());
17719 }
17720
17721 TargetLoweringBase::AtomicRMWExpansionKind
17722 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17723   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17724   const Type *MemType = AI->getType();
17725
17726   // If the operand is too big, we must see if cmpxchg8/16b is available
17727   // and default to library calls otherwise.
17728   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17729     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17730                                    : AtomicRMWExpansionKind::None;
17731   }
17732
17733   AtomicRMWInst::BinOp Op = AI->getOperation();
17734   switch (Op) {
17735   default:
17736     llvm_unreachable("Unknown atomic operation");
17737   case AtomicRMWInst::Xchg:
17738   case AtomicRMWInst::Add:
17739   case AtomicRMWInst::Sub:
17740     // It's better to use xadd, xsub or xchg for these in all cases.
17741     return AtomicRMWExpansionKind::None;
17742   case AtomicRMWInst::Or:
17743   case AtomicRMWInst::And:
17744   case AtomicRMWInst::Xor:
17745     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17746     // prefix to a normal instruction for these operations.
17747     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17748                             : AtomicRMWExpansionKind::None;
17749   case AtomicRMWInst::Nand:
17750   case AtomicRMWInst::Max:
17751   case AtomicRMWInst::Min:
17752   case AtomicRMWInst::UMax:
17753   case AtomicRMWInst::UMin:
17754     // These always require a non-trivial set of data operations on x86. We must
17755     // use a cmpxchg loop.
17756     return AtomicRMWExpansionKind::CmpXChg;
17757   }
17758 }
17759
17760 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17761   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17762   // no-sse2). There isn't any reason to disable it if the target processor
17763   // supports it.
17764   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17765 }
17766
17767 LoadInst *
17768 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17769   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17770   const Type *MemType = AI->getType();
17771   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17772   // there is no benefit in turning such RMWs into loads, and it is actually
17773   // harmful as it introduces a mfence.
17774   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17775     return nullptr;
17776
17777   auto Builder = IRBuilder<>(AI);
17778   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17779   auto SynchScope = AI->getSynchScope();
17780   // We must restrict the ordering to avoid generating loads with Release or
17781   // ReleaseAcquire orderings.
17782   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17783   auto Ptr = AI->getPointerOperand();
17784
17785   // Before the load we need a fence. Here is an example lifted from
17786   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17787   // is required:
17788   // Thread 0:
17789   //   x.store(1, relaxed);
17790   //   r1 = y.fetch_add(0, release);
17791   // Thread 1:
17792   //   y.fetch_add(42, acquire);
17793   //   r2 = x.load(relaxed);
17794   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17795   // lowered to just a load without a fence. A mfence flushes the store buffer,
17796   // making the optimization clearly correct.
17797   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17798   // otherwise, we might be able to be more agressive on relaxed idempotent
17799   // rmw. In practice, they do not look useful, so we don't try to be
17800   // especially clever.
17801   if (SynchScope == SingleThread)
17802     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17803     // the IR level, so we must wrap it in an intrinsic.
17804     return nullptr;
17805
17806   if (!hasMFENCE(*Subtarget))
17807     // FIXME: it might make sense to use a locked operation here but on a
17808     // different cache-line to prevent cache-line bouncing. In practice it
17809     // is probably a small win, and x86 processors without mfence are rare
17810     // enough that we do not bother.
17811     return nullptr;
17812
17813   Function *MFence =
17814       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17815   Builder.CreateCall(MFence, {});
17816
17817   // Finally we can emit the atomic load.
17818   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17819           AI->getType()->getPrimitiveSizeInBits());
17820   Loaded->setAtomic(Order, SynchScope);
17821   AI->replaceAllUsesWith(Loaded);
17822   AI->eraseFromParent();
17823   return Loaded;
17824 }
17825
17826 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17827                                  SelectionDAG &DAG) {
17828   SDLoc dl(Op);
17829   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17830     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17831   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17832     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17833
17834   // The only fence that needs an instruction is a sequentially-consistent
17835   // cross-thread fence.
17836   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17837     if (hasMFENCE(*Subtarget))
17838       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17839
17840     SDValue Chain = Op.getOperand(0);
17841     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17842     SDValue Ops[] = {
17843       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17844       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17845       DAG.getRegister(0, MVT::i32),            // Index
17846       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17847       DAG.getRegister(0, MVT::i32),            // Segment.
17848       Zero,
17849       Chain
17850     };
17851     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17852     return SDValue(Res, 0);
17853   }
17854
17855   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17856   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17857 }
17858
17859 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17860                              SelectionDAG &DAG) {
17861   MVT T = Op.getSimpleValueType();
17862   SDLoc DL(Op);
17863   unsigned Reg = 0;
17864   unsigned size = 0;
17865   switch(T.SimpleTy) {
17866   default: llvm_unreachable("Invalid value type!");
17867   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17868   case MVT::i16: Reg = X86::AX;  size = 2; break;
17869   case MVT::i32: Reg = X86::EAX; size = 4; break;
17870   case MVT::i64:
17871     assert(Subtarget->is64Bit() && "Node not type legal!");
17872     Reg = X86::RAX; size = 8;
17873     break;
17874   }
17875   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17876                                   Op.getOperand(2), SDValue());
17877   SDValue Ops[] = { cpIn.getValue(0),
17878                     Op.getOperand(1),
17879                     Op.getOperand(3),
17880                     DAG.getTargetConstant(size, DL, MVT::i8),
17881                     cpIn.getValue(1) };
17882   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17883   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17884   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17885                                            Ops, T, MMO);
17886
17887   SDValue cpOut =
17888     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17889   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17890                                       MVT::i32, cpOut.getValue(2));
17891   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17892                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17893                                 EFLAGS);
17894
17895   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17896   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17897   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17898   return SDValue();
17899 }
17900
17901 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17902                             SelectionDAG &DAG) {
17903   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17904   MVT DstVT = Op.getSimpleValueType();
17905
17906   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17907     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17908     if (DstVT != MVT::f64)
17909       // This conversion needs to be expanded.
17910       return SDValue();
17911
17912     SDValue InVec = Op->getOperand(0);
17913     SDLoc dl(Op);
17914     unsigned NumElts = SrcVT.getVectorNumElements();
17915     EVT SVT = SrcVT.getVectorElementType();
17916
17917     // Widen the vector in input in the case of MVT::v2i32.
17918     // Example: from MVT::v2i32 to MVT::v4i32.
17919     SmallVector<SDValue, 16> Elts;
17920     for (unsigned i = 0, e = NumElts; i != e; ++i)
17921       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17922                                  DAG.getIntPtrConstant(i, dl)));
17923
17924     // Explicitly mark the extra elements as Undef.
17925     Elts.append(NumElts, DAG.getUNDEF(SVT));
17926
17927     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17928     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17929     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
17930     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17931                        DAG.getIntPtrConstant(0, dl));
17932   }
17933
17934   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17935          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17936   assert((DstVT == MVT::i64 ||
17937           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17938          "Unexpected custom BITCAST");
17939   // i64 <=> MMX conversions are Legal.
17940   if (SrcVT==MVT::i64 && DstVT.isVector())
17941     return Op;
17942   if (DstVT==MVT::i64 && SrcVT.isVector())
17943     return Op;
17944   // MMX <=> MMX conversions are Legal.
17945   if (SrcVT.isVector() && DstVT.isVector())
17946     return Op;
17947   // All other conversions need to be expanded.
17948   return SDValue();
17949 }
17950
17951 /// Compute the horizontal sum of bytes in V for the elements of VT.
17952 ///
17953 /// Requires V to be a byte vector and VT to be an integer vector type with
17954 /// wider elements than V's type. The width of the elements of VT determines
17955 /// how many bytes of V are summed horizontally to produce each element of the
17956 /// result.
17957 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
17958                                       const X86Subtarget *Subtarget,
17959                                       SelectionDAG &DAG) {
17960   SDLoc DL(V);
17961   MVT ByteVecVT = V.getSimpleValueType();
17962   MVT EltVT = VT.getVectorElementType();
17963   int NumElts = VT.getVectorNumElements();
17964   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
17965          "Expected value to have byte element type.");
17966   assert(EltVT != MVT::i8 &&
17967          "Horizontal byte sum only makes sense for wider elements!");
17968   unsigned VecSize = VT.getSizeInBits();
17969   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
17970
17971   // PSADBW instruction horizontally add all bytes and leave the result in i64
17972   // chunks, thus directly computes the pop count for v2i64 and v4i64.
17973   if (EltVT == MVT::i64) {
17974     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17975     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
17976     return DAG.getBitcast(VT, V);
17977   }
17978
17979   if (EltVT == MVT::i32) {
17980     // We unpack the low half and high half into i32s interleaved with zeros so
17981     // that we can use PSADBW to horizontally sum them. The most useful part of
17982     // this is that it lines up the results of two PSADBW instructions to be
17983     // two v2i64 vectors which concatenated are the 4 population counts. We can
17984     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
17985     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
17986     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
17987     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
17988
17989     // Do the horizontal sums into two v2i64s.
17990     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17991     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17992                       DAG.getBitcast(ByteVecVT, Low), Zeros);
17993     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17994                        DAG.getBitcast(ByteVecVT, High), Zeros);
17995
17996     // Merge them together.
17997     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
17998     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
17999                     DAG.getBitcast(ShortVecVT, Low),
18000                     DAG.getBitcast(ShortVecVT, High));
18001
18002     return DAG.getBitcast(VT, V);
18003   }
18004
18005   // The only element type left is i16.
18006   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18007
18008   // To obtain pop count for each i16 element starting from the pop count for
18009   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18010   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18011   // directly supported.
18012   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18013   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18014   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18015   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18016                   DAG.getBitcast(ByteVecVT, V));
18017   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18018 }
18019
18020 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18021                                         const X86Subtarget *Subtarget,
18022                                         SelectionDAG &DAG) {
18023   MVT VT = Op.getSimpleValueType();
18024   MVT EltVT = VT.getVectorElementType();
18025   unsigned VecSize = VT.getSizeInBits();
18026
18027   // Implement a lookup table in register by using an algorithm based on:
18028   // http://wm.ite.pl/articles/sse-popcount.html
18029   //
18030   // The general idea is that every lower byte nibble in the input vector is an
18031   // index into a in-register pre-computed pop count table. We then split up the
18032   // input vector in two new ones: (1) a vector with only the shifted-right
18033   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18034   // masked out higher ones) for each byte. PSHUB is used separately with both
18035   // to index the in-register table. Next, both are added and the result is a
18036   // i8 vector where each element contains the pop count for input byte.
18037   //
18038   // To obtain the pop count for elements != i8, we follow up with the same
18039   // approach and use additional tricks as described below.
18040   //
18041   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18042                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18043                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18044                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18045
18046   int NumByteElts = VecSize / 8;
18047   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18048   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18049   SmallVector<SDValue, 16> LUTVec;
18050   for (int i = 0; i < NumByteElts; ++i)
18051     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18052   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18053   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18054                                   DAG.getConstant(0x0F, DL, MVT::i8));
18055   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18056
18057   // High nibbles
18058   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18059   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18060   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18061
18062   // Low nibbles
18063   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18064
18065   // The input vector is used as the shuffle mask that index elements into the
18066   // LUT. After counting low and high nibbles, add the vector to obtain the
18067   // final pop count per i8 element.
18068   SDValue HighPopCnt =
18069       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18070   SDValue LowPopCnt =
18071       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18072   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18073
18074   if (EltVT == MVT::i8)
18075     return PopCnt;
18076
18077   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18078 }
18079
18080 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18081                                        const X86Subtarget *Subtarget,
18082                                        SelectionDAG &DAG) {
18083   MVT VT = Op.getSimpleValueType();
18084   assert(VT.is128BitVector() &&
18085          "Only 128-bit vector bitmath lowering supported.");
18086
18087   int VecSize = VT.getSizeInBits();
18088   MVT EltVT = VT.getVectorElementType();
18089   int Len = EltVT.getSizeInBits();
18090
18091   // This is the vectorized version of the "best" algorithm from
18092   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18093   // with a minor tweak to use a series of adds + shifts instead of vector
18094   // multiplications. Implemented for all integer vector types. We only use
18095   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18096   // much faster, even faster than using native popcnt instructions.
18097
18098   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18099     MVT VT = V.getSimpleValueType();
18100     SmallVector<SDValue, 32> Shifters(
18101         VT.getVectorNumElements(),
18102         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18103     return DAG.getNode(OpCode, DL, VT, V,
18104                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18105   };
18106   auto GetMask = [&](SDValue V, APInt Mask) {
18107     MVT VT = V.getSimpleValueType();
18108     SmallVector<SDValue, 32> Masks(
18109         VT.getVectorNumElements(),
18110         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18111     return DAG.getNode(ISD::AND, DL, VT, V,
18112                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18113   };
18114
18115   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18116   // x86, so set the SRL type to have elements at least i16 wide. This is
18117   // correct because all of our SRLs are followed immediately by a mask anyways
18118   // that handles any bits that sneak into the high bits of the byte elements.
18119   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18120
18121   SDValue V = Op;
18122
18123   // v = v - ((v >> 1) & 0x55555555...)
18124   SDValue Srl =
18125       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18126   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18127   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18128
18129   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18130   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18131   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18132   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18133   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18134
18135   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18136   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18137   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18138   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18139
18140   // At this point, V contains the byte-wise population count, and we are
18141   // merely doing a horizontal sum if necessary to get the wider element
18142   // counts.
18143   if (EltVT == MVT::i8)
18144     return V;
18145
18146   return LowerHorizontalByteSum(
18147       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18148       DAG);
18149 }
18150
18151 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18152                                 SelectionDAG &DAG) {
18153   MVT VT = Op.getSimpleValueType();
18154   // FIXME: Need to add AVX-512 support here!
18155   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18156          "Unknown CTPOP type to handle");
18157   SDLoc DL(Op.getNode());
18158   SDValue Op0 = Op.getOperand(0);
18159
18160   if (!Subtarget->hasSSSE3()) {
18161     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18162     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18163     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18164   }
18165
18166   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18167     unsigned NumElems = VT.getVectorNumElements();
18168
18169     // Extract each 128-bit vector, compute pop count and concat the result.
18170     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18171     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18172
18173     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18174                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18175                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18176   }
18177
18178   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18179 }
18180
18181 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18182                           SelectionDAG &DAG) {
18183   assert(Op.getValueType().isVector() &&
18184          "We only do custom lowering for vector population count.");
18185   return LowerVectorCTPOP(Op, Subtarget, DAG);
18186 }
18187
18188 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18189   SDNode *Node = Op.getNode();
18190   SDLoc dl(Node);
18191   EVT T = Node->getValueType(0);
18192   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18193                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18194   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18195                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18196                        Node->getOperand(0),
18197                        Node->getOperand(1), negOp,
18198                        cast<AtomicSDNode>(Node)->getMemOperand(),
18199                        cast<AtomicSDNode>(Node)->getOrdering(),
18200                        cast<AtomicSDNode>(Node)->getSynchScope());
18201 }
18202
18203 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18204   SDNode *Node = Op.getNode();
18205   SDLoc dl(Node);
18206   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18207
18208   // Convert seq_cst store -> xchg
18209   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18210   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18211   //        (The only way to get a 16-byte store is cmpxchg16b)
18212   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18213   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18214       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18215     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18216                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18217                                  Node->getOperand(0),
18218                                  Node->getOperand(1), Node->getOperand(2),
18219                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18220                                  cast<AtomicSDNode>(Node)->getOrdering(),
18221                                  cast<AtomicSDNode>(Node)->getSynchScope());
18222     return Swap.getValue(1);
18223   }
18224   // Other atomic stores have a simple pattern.
18225   return Op;
18226 }
18227
18228 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18229   EVT VT = Op.getNode()->getSimpleValueType(0);
18230
18231   // Let legalize expand this if it isn't a legal type yet.
18232   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18233     return SDValue();
18234
18235   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18236
18237   unsigned Opc;
18238   bool ExtraOp = false;
18239   switch (Op.getOpcode()) {
18240   default: llvm_unreachable("Invalid code");
18241   case ISD::ADDC: Opc = X86ISD::ADD; break;
18242   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18243   case ISD::SUBC: Opc = X86ISD::SUB; break;
18244   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18245   }
18246
18247   if (!ExtraOp)
18248     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18249                        Op.getOperand(1));
18250   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18251                      Op.getOperand(1), Op.getOperand(2));
18252 }
18253
18254 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18255                             SelectionDAG &DAG) {
18256   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18257
18258   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18259   // which returns the values as { float, float } (in XMM0) or
18260   // { double, double } (which is returned in XMM0, XMM1).
18261   SDLoc dl(Op);
18262   SDValue Arg = Op.getOperand(0);
18263   EVT ArgVT = Arg.getValueType();
18264   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18265
18266   TargetLowering::ArgListTy Args;
18267   TargetLowering::ArgListEntry Entry;
18268
18269   Entry.Node = Arg;
18270   Entry.Ty = ArgTy;
18271   Entry.isSExt = false;
18272   Entry.isZExt = false;
18273   Args.push_back(Entry);
18274
18275   bool isF64 = ArgVT == MVT::f64;
18276   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18277   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18278   // the results are returned via SRet in memory.
18279   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18280   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18281   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
18282
18283   Type *RetTy = isF64
18284     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18285     : (Type*)VectorType::get(ArgTy, 4);
18286
18287   TargetLowering::CallLoweringInfo CLI(DAG);
18288   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18289     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18290
18291   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18292
18293   if (isF64)
18294     // Returned in xmm0 and xmm1.
18295     return CallResult.first;
18296
18297   // Returned in bits 0:31 and 32:64 xmm0.
18298   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18299                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18300   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18301                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18302   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18303   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18304 }
18305
18306 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18307                              SelectionDAG &DAG) {
18308   assert(Subtarget->hasAVX512() &&
18309          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18310
18311   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18312   EVT VT = N->getValue().getValueType();
18313   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18314   SDLoc dl(Op);
18315
18316   // X86 scatter kills mask register, so its type should be added to
18317   // the list of return values
18318   if (N->getNumValues() == 1) {
18319     SDValue Index = N->getIndex();
18320     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18321         !Index.getValueType().is512BitVector())
18322       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18323
18324     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18325     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18326                       N->getOperand(3), Index };
18327
18328     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18329     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18330     return SDValue(NewScatter.getNode(), 0);
18331   }
18332   return Op;
18333 }
18334
18335 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18336                             SelectionDAG &DAG) {
18337   assert(Subtarget->hasAVX512() &&
18338          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18339
18340   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18341   EVT VT = Op.getValueType();
18342   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18343   SDLoc dl(Op);
18344
18345   SDValue Index = N->getIndex();
18346   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18347       !Index.getValueType().is512BitVector()) {
18348     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18349     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18350                       N->getOperand(3), Index };
18351     DAG.UpdateNodeOperands(N, Ops);
18352   }
18353   return Op;
18354 }
18355
18356 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18357                                                     SelectionDAG &DAG) const {
18358   // TODO: Eventually, the lowering of these nodes should be informed by or
18359   // deferred to the GC strategy for the function in which they appear. For
18360   // now, however, they must be lowered to something. Since they are logically
18361   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18362   // require special handling for these nodes), lower them as literal NOOPs for
18363   // the time being.
18364   SmallVector<SDValue, 2> Ops;
18365
18366   Ops.push_back(Op.getOperand(0));
18367   if (Op->getGluedNode())
18368     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18369
18370   SDLoc OpDL(Op);
18371   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18372   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18373
18374   return NOOP;
18375 }
18376
18377 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18378                                                   SelectionDAG &DAG) const {
18379   // TODO: Eventually, the lowering of these nodes should be informed by or
18380   // deferred to the GC strategy for the function in which they appear. For
18381   // now, however, they must be lowered to something. Since they are logically
18382   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18383   // require special handling for these nodes), lower them as literal NOOPs for
18384   // the time being.
18385   SmallVector<SDValue, 2> Ops;
18386
18387   Ops.push_back(Op.getOperand(0));
18388   if (Op->getGluedNode())
18389     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18390
18391   SDLoc OpDL(Op);
18392   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18393   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18394
18395   return NOOP;
18396 }
18397
18398 /// LowerOperation - Provide custom lowering hooks for some operations.
18399 ///
18400 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18401   switch (Op.getOpcode()) {
18402   default: llvm_unreachable("Should not custom lower this!");
18403   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18404   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18405     return LowerCMP_SWAP(Op, Subtarget, DAG);
18406   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18407   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18408   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18409   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18410   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18411   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18412   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18413   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18414   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18415   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18416   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18417   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18418   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18419   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18420   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18421   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18422   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18423   case ISD::SHL_PARTS:
18424   case ISD::SRA_PARTS:
18425   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18426   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18427   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18428   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18429   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18430   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18431   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18432   case ISD::SIGN_EXTEND_VECTOR_INREG:
18433     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18434   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18435   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18436   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18437   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18438   case ISD::FABS:
18439   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18440   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18441   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18442   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18443   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18444   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18445   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18446   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18447   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18448   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18449   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18450   case ISD::INTRINSIC_VOID:
18451   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18452   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18453   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18454   case ISD::FRAME_TO_ARGS_OFFSET:
18455                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18456   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18457   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18458   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18459   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18460   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18461   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18462   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18463   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18464   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18465   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18466   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18467   case ISD::UMUL_LOHI:
18468   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18469   case ISD::SRA:
18470   case ISD::SRL:
18471   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18472   case ISD::SADDO:
18473   case ISD::UADDO:
18474   case ISD::SSUBO:
18475   case ISD::USUBO:
18476   case ISD::SMULO:
18477   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18478   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18479   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18480   case ISD::ADDC:
18481   case ISD::ADDE:
18482   case ISD::SUBC:
18483   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18484   case ISD::ADD:                return LowerADD(Op, DAG);
18485   case ISD::SUB:                return LowerSUB(Op, DAG);
18486   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18487   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18488   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18489   case ISD::GC_TRANSITION_START:
18490                                 return LowerGC_TRANSITION_START(Op, DAG);
18491   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18492   }
18493 }
18494
18495 /// ReplaceNodeResults - Replace a node with an illegal result type
18496 /// with a new node built out of custom code.
18497 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18498                                            SmallVectorImpl<SDValue>&Results,
18499                                            SelectionDAG &DAG) const {
18500   SDLoc dl(N);
18501   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18502   switch (N->getOpcode()) {
18503   default:
18504     llvm_unreachable("Do not know how to custom type legalize this operation!");
18505   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18506   case X86ISD::FMINC:
18507   case X86ISD::FMIN:
18508   case X86ISD::FMAXC:
18509   case X86ISD::FMAX: {
18510     EVT VT = N->getValueType(0);
18511     if (VT != MVT::v2f32)
18512       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18513     SDValue UNDEF = DAG.getUNDEF(VT);
18514     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18515                               N->getOperand(0), UNDEF);
18516     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18517                               N->getOperand(1), UNDEF);
18518     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18519     return;
18520   }
18521   case ISD::SIGN_EXTEND_INREG:
18522   case ISD::ADDC:
18523   case ISD::ADDE:
18524   case ISD::SUBC:
18525   case ISD::SUBE:
18526     // We don't want to expand or promote these.
18527     return;
18528   case ISD::SDIV:
18529   case ISD::UDIV:
18530   case ISD::SREM:
18531   case ISD::UREM:
18532   case ISD::SDIVREM:
18533   case ISD::UDIVREM: {
18534     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18535     Results.push_back(V);
18536     return;
18537   }
18538   case ISD::FP_TO_SINT:
18539     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18540     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18541     if (N->getOperand(0).getValueType() == MVT::f16)
18542       break;
18543     // fallthrough
18544   case ISD::FP_TO_UINT: {
18545     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18546
18547     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18548       return;
18549
18550     std::pair<SDValue,SDValue> Vals =
18551         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18552     SDValue FIST = Vals.first, StackSlot = Vals.second;
18553     if (FIST.getNode()) {
18554       EVT VT = N->getValueType(0);
18555       // Return a load from the stack slot.
18556       if (StackSlot.getNode())
18557         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18558                                       MachinePointerInfo(),
18559                                       false, false, false, 0));
18560       else
18561         Results.push_back(FIST);
18562     }
18563     return;
18564   }
18565   case ISD::UINT_TO_FP: {
18566     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18567     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18568         N->getValueType(0) != MVT::v2f32)
18569       return;
18570     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18571                                  N->getOperand(0));
18572     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18573                                      MVT::f64);
18574     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18575     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18576                              DAG.getBitcast(MVT::v2i64, VBias));
18577     Or = DAG.getBitcast(MVT::v2f64, Or);
18578     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18579     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18580     return;
18581   }
18582   case ISD::FP_ROUND: {
18583     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18584         return;
18585     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18586     Results.push_back(V);
18587     return;
18588   }
18589   case ISD::FP_EXTEND: {
18590     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18591     // No other ValueType for FP_EXTEND should reach this point.
18592     assert(N->getValueType(0) == MVT::v2f32 &&
18593            "Do not know how to legalize this Node");
18594     return;
18595   }
18596   case ISD::INTRINSIC_W_CHAIN: {
18597     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18598     switch (IntNo) {
18599     default : llvm_unreachable("Do not know how to custom type "
18600                                "legalize this intrinsic operation!");
18601     case Intrinsic::x86_rdtsc:
18602       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18603                                      Results);
18604     case Intrinsic::x86_rdtscp:
18605       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18606                                      Results);
18607     case Intrinsic::x86_rdpmc:
18608       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18609     }
18610   }
18611   case ISD::READCYCLECOUNTER: {
18612     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18613                                    Results);
18614   }
18615   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18616     EVT T = N->getValueType(0);
18617     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18618     bool Regs64bit = T == MVT::i128;
18619     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18620     SDValue cpInL, cpInH;
18621     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18622                         DAG.getConstant(0, dl, HalfT));
18623     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18624                         DAG.getConstant(1, dl, HalfT));
18625     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18626                              Regs64bit ? X86::RAX : X86::EAX,
18627                              cpInL, SDValue());
18628     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18629                              Regs64bit ? X86::RDX : X86::EDX,
18630                              cpInH, cpInL.getValue(1));
18631     SDValue swapInL, swapInH;
18632     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18633                           DAG.getConstant(0, dl, HalfT));
18634     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18635                           DAG.getConstant(1, dl, HalfT));
18636     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18637                                Regs64bit ? X86::RBX : X86::EBX,
18638                                swapInL, cpInH.getValue(1));
18639     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18640                                Regs64bit ? X86::RCX : X86::ECX,
18641                                swapInH, swapInL.getValue(1));
18642     SDValue Ops[] = { swapInH.getValue(0),
18643                       N->getOperand(1),
18644                       swapInH.getValue(1) };
18645     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18646     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18647     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18648                                   X86ISD::LCMPXCHG8_DAG;
18649     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18650     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18651                                         Regs64bit ? X86::RAX : X86::EAX,
18652                                         HalfT, Result.getValue(1));
18653     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18654                                         Regs64bit ? X86::RDX : X86::EDX,
18655                                         HalfT, cpOutL.getValue(2));
18656     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18657
18658     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18659                                         MVT::i32, cpOutH.getValue(2));
18660     SDValue Success =
18661         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18662                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18663     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18664
18665     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18666     Results.push_back(Success);
18667     Results.push_back(EFLAGS.getValue(1));
18668     return;
18669   }
18670   case ISD::ATOMIC_SWAP:
18671   case ISD::ATOMIC_LOAD_ADD:
18672   case ISD::ATOMIC_LOAD_SUB:
18673   case ISD::ATOMIC_LOAD_AND:
18674   case ISD::ATOMIC_LOAD_OR:
18675   case ISD::ATOMIC_LOAD_XOR:
18676   case ISD::ATOMIC_LOAD_NAND:
18677   case ISD::ATOMIC_LOAD_MIN:
18678   case ISD::ATOMIC_LOAD_MAX:
18679   case ISD::ATOMIC_LOAD_UMIN:
18680   case ISD::ATOMIC_LOAD_UMAX:
18681   case ISD::ATOMIC_LOAD: {
18682     // Delegate to generic TypeLegalization. Situations we can really handle
18683     // should have already been dealt with by AtomicExpandPass.cpp.
18684     break;
18685   }
18686   case ISD::BITCAST: {
18687     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18688     EVT DstVT = N->getValueType(0);
18689     EVT SrcVT = N->getOperand(0)->getValueType(0);
18690
18691     if (SrcVT != MVT::f64 ||
18692         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18693       return;
18694
18695     unsigned NumElts = DstVT.getVectorNumElements();
18696     EVT SVT = DstVT.getVectorElementType();
18697     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18698     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18699                                    MVT::v2f64, N->getOperand(0));
18700     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18701
18702     if (ExperimentalVectorWideningLegalization) {
18703       // If we are legalizing vectors by widening, we already have the desired
18704       // legal vector type, just return it.
18705       Results.push_back(ToVecInt);
18706       return;
18707     }
18708
18709     SmallVector<SDValue, 8> Elts;
18710     for (unsigned i = 0, e = NumElts; i != e; ++i)
18711       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18712                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18713
18714     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18715   }
18716   }
18717 }
18718
18719 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18720   switch ((X86ISD::NodeType)Opcode) {
18721   case X86ISD::FIRST_NUMBER:       break;
18722   case X86ISD::BSF:                return "X86ISD::BSF";
18723   case X86ISD::BSR:                return "X86ISD::BSR";
18724   case X86ISD::SHLD:               return "X86ISD::SHLD";
18725   case X86ISD::SHRD:               return "X86ISD::SHRD";
18726   case X86ISD::FAND:               return "X86ISD::FAND";
18727   case X86ISD::FANDN:              return "X86ISD::FANDN";
18728   case X86ISD::FOR:                return "X86ISD::FOR";
18729   case X86ISD::FXOR:               return "X86ISD::FXOR";
18730   case X86ISD::FILD:               return "X86ISD::FILD";
18731   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18732   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18733   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18734   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18735   case X86ISD::FLD:                return "X86ISD::FLD";
18736   case X86ISD::FST:                return "X86ISD::FST";
18737   case X86ISD::CALL:               return "X86ISD::CALL";
18738   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18739   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18740   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18741   case X86ISD::BT:                 return "X86ISD::BT";
18742   case X86ISD::CMP:                return "X86ISD::CMP";
18743   case X86ISD::COMI:               return "X86ISD::COMI";
18744   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18745   case X86ISD::CMPM:               return "X86ISD::CMPM";
18746   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18747   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18748   case X86ISD::SETCC:              return "X86ISD::SETCC";
18749   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18750   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18751   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18752   case X86ISD::CMOV:               return "X86ISD::CMOV";
18753   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18754   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18755   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18756   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18757   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18758   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18759   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18760   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18761   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18762   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18763   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18764   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18765   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18766   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18767   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18768   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18769   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18770   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18771   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18772   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18773   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18774   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18775   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18776   case X86ISD::HADD:               return "X86ISD::HADD";
18777   case X86ISD::HSUB:               return "X86ISD::HSUB";
18778   case X86ISD::FHADD:              return "X86ISD::FHADD";
18779   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18780   case X86ISD::ABS:                return "X86ISD::ABS";
18781   case X86ISD::FMAX:               return "X86ISD::FMAX";
18782   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18783   case X86ISD::FMIN:               return "X86ISD::FMIN";
18784   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18785   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18786   case X86ISD::FMINC:              return "X86ISD::FMINC";
18787   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18788   case X86ISD::FRCP:               return "X86ISD::FRCP";
18789   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
18790   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
18791   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18792   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18793   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18794   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18795   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18796   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18797   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18798   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18799   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18800   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18801   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18802   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18803   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18804   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18805   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18806   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18807   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18808   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18809   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18810   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18811   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18812   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18813   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18814   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18815   case X86ISD::VSHL:               return "X86ISD::VSHL";
18816   case X86ISD::VSRL:               return "X86ISD::VSRL";
18817   case X86ISD::VSRA:               return "X86ISD::VSRA";
18818   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18819   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18820   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18821   case X86ISD::CMPP:               return "X86ISD::CMPP";
18822   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18823   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18824   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18825   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18826   case X86ISD::ADD:                return "X86ISD::ADD";
18827   case X86ISD::SUB:                return "X86ISD::SUB";
18828   case X86ISD::ADC:                return "X86ISD::ADC";
18829   case X86ISD::SBB:                return "X86ISD::SBB";
18830   case X86ISD::SMUL:               return "X86ISD::SMUL";
18831   case X86ISD::UMUL:               return "X86ISD::UMUL";
18832   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18833   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18834   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18835   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18836   case X86ISD::INC:                return "X86ISD::INC";
18837   case X86ISD::DEC:                return "X86ISD::DEC";
18838   case X86ISD::OR:                 return "X86ISD::OR";
18839   case X86ISD::XOR:                return "X86ISD::XOR";
18840   case X86ISD::AND:                return "X86ISD::AND";
18841   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18842   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18843   case X86ISD::PTEST:              return "X86ISD::PTEST";
18844   case X86ISD::TESTP:              return "X86ISD::TESTP";
18845   case X86ISD::TESTM:              return "X86ISD::TESTM";
18846   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18847   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18848   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18849   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18850   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18851   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18852   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18853   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18854   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18855   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18856   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
18857   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18858   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18859   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18860   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18861   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18862   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18863   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18864   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18865   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18866   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18867   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18868   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18869   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18870   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18871   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18872   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18873   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18874   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18875   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18876   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18877   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18878   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18879   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
18880   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
18881   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18882   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18883   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
18884   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18885   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18886   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18887   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18888   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18889   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18890   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18891   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18892   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18893   case X86ISD::SAHF:               return "X86ISD::SAHF";
18894   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18895   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18896   case X86ISD::FMADD:              return "X86ISD::FMADD";
18897   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18898   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18899   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18900   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18901   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18902   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18903   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18904   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18905   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18906   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18907   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18908   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18909   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18910   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18911   case X86ISD::XTEST:              return "X86ISD::XTEST";
18912   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18913   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18914   case X86ISD::SELECT:             return "X86ISD::SELECT";
18915   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18916   case X86ISD::RCP28:              return "X86ISD::RCP28";
18917   case X86ISD::EXP2:               return "X86ISD::EXP2";
18918   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18919   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18920   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18921   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18922   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18923   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
18924   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
18925   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
18926   case X86ISD::ADDS:               return "X86ISD::ADDS";
18927   case X86ISD::SUBS:               return "X86ISD::SUBS";
18928   case X86ISD::AVG:                return "X86ISD::AVG";
18929   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
18930   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
18931   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
18932   }
18933   return nullptr;
18934 }
18935
18936 // isLegalAddressingMode - Return true if the addressing mode represented
18937 // by AM is legal for this target, for a load/store of the specified type.
18938 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18939                                               Type *Ty,
18940                                               unsigned AS) const {
18941   // X86 supports extremely general addressing modes.
18942   CodeModel::Model M = getTargetMachine().getCodeModel();
18943   Reloc::Model R = getTargetMachine().getRelocationModel();
18944
18945   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18946   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18947     return false;
18948
18949   if (AM.BaseGV) {
18950     unsigned GVFlags =
18951       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18952
18953     // If a reference to this global requires an extra load, we can't fold it.
18954     if (isGlobalStubReference(GVFlags))
18955       return false;
18956
18957     // If BaseGV requires a register for the PIC base, we cannot also have a
18958     // BaseReg specified.
18959     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18960       return false;
18961
18962     // If lower 4G is not available, then we must use rip-relative addressing.
18963     if ((M != CodeModel::Small || R != Reloc::Static) &&
18964         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18965       return false;
18966   }
18967
18968   switch (AM.Scale) {
18969   case 0:
18970   case 1:
18971   case 2:
18972   case 4:
18973   case 8:
18974     // These scales always work.
18975     break;
18976   case 3:
18977   case 5:
18978   case 9:
18979     // These scales are formed with basereg+scalereg.  Only accept if there is
18980     // no basereg yet.
18981     if (AM.HasBaseReg)
18982       return false;
18983     break;
18984   default:  // Other stuff never works.
18985     return false;
18986   }
18987
18988   return true;
18989 }
18990
18991 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18992   unsigned Bits = Ty->getScalarSizeInBits();
18993
18994   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18995   // particularly cheaper than those without.
18996   if (Bits == 8)
18997     return false;
18998
18999   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19000   // variable shifts just as cheap as scalar ones.
19001   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19002     return false;
19003
19004   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19005   // fully general vector.
19006   return true;
19007 }
19008
19009 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19010   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19011     return false;
19012   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19013   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19014   return NumBits1 > NumBits2;
19015 }
19016
19017 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19018   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19019     return false;
19020
19021   if (!isTypeLegal(EVT::getEVT(Ty1)))
19022     return false;
19023
19024   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19025
19026   // Assuming the caller doesn't have a zeroext or signext return parameter,
19027   // truncation all the way down to i1 is valid.
19028   return true;
19029 }
19030
19031 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19032   return isInt<32>(Imm);
19033 }
19034
19035 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19036   // Can also use sub to handle negated immediates.
19037   return isInt<32>(Imm);
19038 }
19039
19040 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19041   if (!VT1.isInteger() || !VT2.isInteger())
19042     return false;
19043   unsigned NumBits1 = VT1.getSizeInBits();
19044   unsigned NumBits2 = VT2.getSizeInBits();
19045   return NumBits1 > NumBits2;
19046 }
19047
19048 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19049   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19050   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19051 }
19052
19053 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19054   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19055   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19056 }
19057
19058 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19059   EVT VT1 = Val.getValueType();
19060   if (isZExtFree(VT1, VT2))
19061     return true;
19062
19063   if (Val.getOpcode() != ISD::LOAD)
19064     return false;
19065
19066   if (!VT1.isSimple() || !VT1.isInteger() ||
19067       !VT2.isSimple() || !VT2.isInteger())
19068     return false;
19069
19070   switch (VT1.getSimpleVT().SimpleTy) {
19071   default: break;
19072   case MVT::i8:
19073   case MVT::i16:
19074   case MVT::i32:
19075     // X86 has 8, 16, and 32-bit zero-extending loads.
19076     return true;
19077   }
19078
19079   return false;
19080 }
19081
19082 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19083
19084 bool
19085 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19086   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19087     return false;
19088
19089   VT = VT.getScalarType();
19090
19091   if (!VT.isSimple())
19092     return false;
19093
19094   switch (VT.getSimpleVT().SimpleTy) {
19095   case MVT::f32:
19096   case MVT::f64:
19097     return true;
19098   default:
19099     break;
19100   }
19101
19102   return false;
19103 }
19104
19105 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19106   // i16 instructions are longer (0x66 prefix) and potentially slower.
19107   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19108 }
19109
19110 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19111 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19112 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19113 /// are assumed to be legal.
19114 bool
19115 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19116                                       EVT VT) const {
19117   if (!VT.isSimple())
19118     return false;
19119
19120   // Not for i1 vectors
19121   if (VT.getScalarType() == MVT::i1)
19122     return false;
19123
19124   // Very little shuffling can be done for 64-bit vectors right now.
19125   if (VT.getSizeInBits() == 64)
19126     return false;
19127
19128   // We only care that the types being shuffled are legal. The lowering can
19129   // handle any possible shuffle mask that results.
19130   return isTypeLegal(VT.getSimpleVT());
19131 }
19132
19133 bool
19134 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19135                                           EVT VT) const {
19136   // Just delegate to the generic legality, clear masks aren't special.
19137   return isShuffleMaskLegal(Mask, VT);
19138 }
19139
19140 //===----------------------------------------------------------------------===//
19141 //                           X86 Scheduler Hooks
19142 //===----------------------------------------------------------------------===//
19143
19144 /// Utility function to emit xbegin specifying the start of an RTM region.
19145 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19146                                      const TargetInstrInfo *TII) {
19147   DebugLoc DL = MI->getDebugLoc();
19148
19149   const BasicBlock *BB = MBB->getBasicBlock();
19150   MachineFunction::iterator I = MBB;
19151   ++I;
19152
19153   // For the v = xbegin(), we generate
19154   //
19155   // thisMBB:
19156   //  xbegin sinkMBB
19157   //
19158   // mainMBB:
19159   //  eax = -1
19160   //
19161   // sinkMBB:
19162   //  v = eax
19163
19164   MachineBasicBlock *thisMBB = MBB;
19165   MachineFunction *MF = MBB->getParent();
19166   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19167   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19168   MF->insert(I, mainMBB);
19169   MF->insert(I, sinkMBB);
19170
19171   // Transfer the remainder of BB and its successor edges to sinkMBB.
19172   sinkMBB->splice(sinkMBB->begin(), MBB,
19173                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19174   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19175
19176   // thisMBB:
19177   //  xbegin sinkMBB
19178   //  # fallthrough to mainMBB
19179   //  # abortion to sinkMBB
19180   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19181   thisMBB->addSuccessor(mainMBB);
19182   thisMBB->addSuccessor(sinkMBB);
19183
19184   // mainMBB:
19185   //  EAX = -1
19186   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19187   mainMBB->addSuccessor(sinkMBB);
19188
19189   // sinkMBB:
19190   // EAX is live into the sinkMBB
19191   sinkMBB->addLiveIn(X86::EAX);
19192   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19193           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19194     .addReg(X86::EAX);
19195
19196   MI->eraseFromParent();
19197   return sinkMBB;
19198 }
19199
19200 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19201 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19202 // in the .td file.
19203 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19204                                        const TargetInstrInfo *TII) {
19205   unsigned Opc;
19206   switch (MI->getOpcode()) {
19207   default: llvm_unreachable("illegal opcode!");
19208   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19209   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19210   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19211   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19212   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19213   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19214   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19215   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19216   }
19217
19218   DebugLoc dl = MI->getDebugLoc();
19219   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19220
19221   unsigned NumArgs = MI->getNumOperands();
19222   for (unsigned i = 1; i < NumArgs; ++i) {
19223     MachineOperand &Op = MI->getOperand(i);
19224     if (!(Op.isReg() && Op.isImplicit()))
19225       MIB.addOperand(Op);
19226   }
19227   if (MI->hasOneMemOperand())
19228     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19229
19230   BuildMI(*BB, MI, dl,
19231     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19232     .addReg(X86::XMM0);
19233
19234   MI->eraseFromParent();
19235   return BB;
19236 }
19237
19238 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19239 // defs in an instruction pattern
19240 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19241                                        const TargetInstrInfo *TII) {
19242   unsigned Opc;
19243   switch (MI->getOpcode()) {
19244   default: llvm_unreachable("illegal opcode!");
19245   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19246   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19247   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19248   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19249   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19250   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19251   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19252   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19253   }
19254
19255   DebugLoc dl = MI->getDebugLoc();
19256   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19257
19258   unsigned NumArgs = MI->getNumOperands(); // remove the results
19259   for (unsigned i = 1; i < NumArgs; ++i) {
19260     MachineOperand &Op = MI->getOperand(i);
19261     if (!(Op.isReg() && Op.isImplicit()))
19262       MIB.addOperand(Op);
19263   }
19264   if (MI->hasOneMemOperand())
19265     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19266
19267   BuildMI(*BB, MI, dl,
19268     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19269     .addReg(X86::ECX);
19270
19271   MI->eraseFromParent();
19272   return BB;
19273 }
19274
19275 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19276                                       const X86Subtarget *Subtarget) {
19277   DebugLoc dl = MI->getDebugLoc();
19278   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19279   // Address into RAX/EAX, other two args into ECX, EDX.
19280   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19281   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19282   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19283   for (int i = 0; i < X86::AddrNumOperands; ++i)
19284     MIB.addOperand(MI->getOperand(i));
19285
19286   unsigned ValOps = X86::AddrNumOperands;
19287   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19288     .addReg(MI->getOperand(ValOps).getReg());
19289   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19290     .addReg(MI->getOperand(ValOps+1).getReg());
19291
19292   // The instruction doesn't actually take any operands though.
19293   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19294
19295   MI->eraseFromParent(); // The pseudo is gone now.
19296   return BB;
19297 }
19298
19299 MachineBasicBlock *
19300 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19301                                                  MachineBasicBlock *MBB) const {
19302   // Emit va_arg instruction on X86-64.
19303
19304   // Operands to this pseudo-instruction:
19305   // 0  ) Output        : destination address (reg)
19306   // 1-5) Input         : va_list address (addr, i64mem)
19307   // 6  ) ArgSize       : Size (in bytes) of vararg type
19308   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19309   // 8  ) Align         : Alignment of type
19310   // 9  ) EFLAGS (implicit-def)
19311
19312   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19313   static_assert(X86::AddrNumOperands == 5,
19314                 "VAARG_64 assumes 5 address operands");
19315
19316   unsigned DestReg = MI->getOperand(0).getReg();
19317   MachineOperand &Base = MI->getOperand(1);
19318   MachineOperand &Scale = MI->getOperand(2);
19319   MachineOperand &Index = MI->getOperand(3);
19320   MachineOperand &Disp = MI->getOperand(4);
19321   MachineOperand &Segment = MI->getOperand(5);
19322   unsigned ArgSize = MI->getOperand(6).getImm();
19323   unsigned ArgMode = MI->getOperand(7).getImm();
19324   unsigned Align = MI->getOperand(8).getImm();
19325
19326   // Memory Reference
19327   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19328   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19329   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19330
19331   // Machine Information
19332   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19333   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19334   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19335   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19336   DebugLoc DL = MI->getDebugLoc();
19337
19338   // struct va_list {
19339   //   i32   gp_offset
19340   //   i32   fp_offset
19341   //   i64   overflow_area (address)
19342   //   i64   reg_save_area (address)
19343   // }
19344   // sizeof(va_list) = 24
19345   // alignment(va_list) = 8
19346
19347   unsigned TotalNumIntRegs = 6;
19348   unsigned TotalNumXMMRegs = 8;
19349   bool UseGPOffset = (ArgMode == 1);
19350   bool UseFPOffset = (ArgMode == 2);
19351   unsigned MaxOffset = TotalNumIntRegs * 8 +
19352                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19353
19354   /* Align ArgSize to a multiple of 8 */
19355   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19356   bool NeedsAlign = (Align > 8);
19357
19358   MachineBasicBlock *thisMBB = MBB;
19359   MachineBasicBlock *overflowMBB;
19360   MachineBasicBlock *offsetMBB;
19361   MachineBasicBlock *endMBB;
19362
19363   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19364   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19365   unsigned OffsetReg = 0;
19366
19367   if (!UseGPOffset && !UseFPOffset) {
19368     // If we only pull from the overflow region, we don't create a branch.
19369     // We don't need to alter control flow.
19370     OffsetDestReg = 0; // unused
19371     OverflowDestReg = DestReg;
19372
19373     offsetMBB = nullptr;
19374     overflowMBB = thisMBB;
19375     endMBB = thisMBB;
19376   } else {
19377     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19378     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19379     // If not, pull from overflow_area. (branch to overflowMBB)
19380     //
19381     //       thisMBB
19382     //         |     .
19383     //         |        .
19384     //     offsetMBB   overflowMBB
19385     //         |        .
19386     //         |     .
19387     //        endMBB
19388
19389     // Registers for the PHI in endMBB
19390     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19391     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19392
19393     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19394     MachineFunction *MF = MBB->getParent();
19395     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19396     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19397     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19398
19399     MachineFunction::iterator MBBIter = MBB;
19400     ++MBBIter;
19401
19402     // Insert the new basic blocks
19403     MF->insert(MBBIter, offsetMBB);
19404     MF->insert(MBBIter, overflowMBB);
19405     MF->insert(MBBIter, endMBB);
19406
19407     // Transfer the remainder of MBB and its successor edges to endMBB.
19408     endMBB->splice(endMBB->begin(), thisMBB,
19409                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19410     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19411
19412     // Make offsetMBB and overflowMBB successors of thisMBB
19413     thisMBB->addSuccessor(offsetMBB);
19414     thisMBB->addSuccessor(overflowMBB);
19415
19416     // endMBB is a successor of both offsetMBB and overflowMBB
19417     offsetMBB->addSuccessor(endMBB);
19418     overflowMBB->addSuccessor(endMBB);
19419
19420     // Load the offset value into a register
19421     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19422     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19423       .addOperand(Base)
19424       .addOperand(Scale)
19425       .addOperand(Index)
19426       .addDisp(Disp, UseFPOffset ? 4 : 0)
19427       .addOperand(Segment)
19428       .setMemRefs(MMOBegin, MMOEnd);
19429
19430     // Check if there is enough room left to pull this argument.
19431     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19432       .addReg(OffsetReg)
19433       .addImm(MaxOffset + 8 - ArgSizeA8);
19434
19435     // Branch to "overflowMBB" if offset >= max
19436     // Fall through to "offsetMBB" otherwise
19437     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19438       .addMBB(overflowMBB);
19439   }
19440
19441   // In offsetMBB, emit code to use the reg_save_area.
19442   if (offsetMBB) {
19443     assert(OffsetReg != 0);
19444
19445     // Read the reg_save_area address.
19446     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19447     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19448       .addOperand(Base)
19449       .addOperand(Scale)
19450       .addOperand(Index)
19451       .addDisp(Disp, 16)
19452       .addOperand(Segment)
19453       .setMemRefs(MMOBegin, MMOEnd);
19454
19455     // Zero-extend the offset
19456     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19457       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19458         .addImm(0)
19459         .addReg(OffsetReg)
19460         .addImm(X86::sub_32bit);
19461
19462     // Add the offset to the reg_save_area to get the final address.
19463     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19464       .addReg(OffsetReg64)
19465       .addReg(RegSaveReg);
19466
19467     // Compute the offset for the next argument
19468     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19469     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19470       .addReg(OffsetReg)
19471       .addImm(UseFPOffset ? 16 : 8);
19472
19473     // Store it back into the va_list.
19474     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19475       .addOperand(Base)
19476       .addOperand(Scale)
19477       .addOperand(Index)
19478       .addDisp(Disp, UseFPOffset ? 4 : 0)
19479       .addOperand(Segment)
19480       .addReg(NextOffsetReg)
19481       .setMemRefs(MMOBegin, MMOEnd);
19482
19483     // Jump to endMBB
19484     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19485       .addMBB(endMBB);
19486   }
19487
19488   //
19489   // Emit code to use overflow area
19490   //
19491
19492   // Load the overflow_area address into a register.
19493   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19494   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19495     .addOperand(Base)
19496     .addOperand(Scale)
19497     .addOperand(Index)
19498     .addDisp(Disp, 8)
19499     .addOperand(Segment)
19500     .setMemRefs(MMOBegin, MMOEnd);
19501
19502   // If we need to align it, do so. Otherwise, just copy the address
19503   // to OverflowDestReg.
19504   if (NeedsAlign) {
19505     // Align the overflow address
19506     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19507     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19508
19509     // aligned_addr = (addr + (align-1)) & ~(align-1)
19510     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19511       .addReg(OverflowAddrReg)
19512       .addImm(Align-1);
19513
19514     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19515       .addReg(TmpReg)
19516       .addImm(~(uint64_t)(Align-1));
19517   } else {
19518     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19519       .addReg(OverflowAddrReg);
19520   }
19521
19522   // Compute the next overflow address after this argument.
19523   // (the overflow address should be kept 8-byte aligned)
19524   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19525   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19526     .addReg(OverflowDestReg)
19527     .addImm(ArgSizeA8);
19528
19529   // Store the new overflow address.
19530   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19531     .addOperand(Base)
19532     .addOperand(Scale)
19533     .addOperand(Index)
19534     .addDisp(Disp, 8)
19535     .addOperand(Segment)
19536     .addReg(NextAddrReg)
19537     .setMemRefs(MMOBegin, MMOEnd);
19538
19539   // If we branched, emit the PHI to the front of endMBB.
19540   if (offsetMBB) {
19541     BuildMI(*endMBB, endMBB->begin(), DL,
19542             TII->get(X86::PHI), DestReg)
19543       .addReg(OffsetDestReg).addMBB(offsetMBB)
19544       .addReg(OverflowDestReg).addMBB(overflowMBB);
19545   }
19546
19547   // Erase the pseudo instruction
19548   MI->eraseFromParent();
19549
19550   return endMBB;
19551 }
19552
19553 MachineBasicBlock *
19554 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19555                                                  MachineInstr *MI,
19556                                                  MachineBasicBlock *MBB) const {
19557   // Emit code to save XMM registers to the stack. The ABI says that the
19558   // number of registers to save is given in %al, so it's theoretically
19559   // possible to do an indirect jump trick to avoid saving all of them,
19560   // however this code takes a simpler approach and just executes all
19561   // of the stores if %al is non-zero. It's less code, and it's probably
19562   // easier on the hardware branch predictor, and stores aren't all that
19563   // expensive anyway.
19564
19565   // Create the new basic blocks. One block contains all the XMM stores,
19566   // and one block is the final destination regardless of whether any
19567   // stores were performed.
19568   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19569   MachineFunction *F = MBB->getParent();
19570   MachineFunction::iterator MBBIter = MBB;
19571   ++MBBIter;
19572   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19573   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19574   F->insert(MBBIter, XMMSaveMBB);
19575   F->insert(MBBIter, EndMBB);
19576
19577   // Transfer the remainder of MBB and its successor edges to EndMBB.
19578   EndMBB->splice(EndMBB->begin(), MBB,
19579                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19580   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19581
19582   // The original block will now fall through to the XMM save block.
19583   MBB->addSuccessor(XMMSaveMBB);
19584   // The XMMSaveMBB will fall through to the end block.
19585   XMMSaveMBB->addSuccessor(EndMBB);
19586
19587   // Now add the instructions.
19588   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19589   DebugLoc DL = MI->getDebugLoc();
19590
19591   unsigned CountReg = MI->getOperand(0).getReg();
19592   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19593   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19594
19595   if (!Subtarget->isTargetWin64()) {
19596     // If %al is 0, branch around the XMM save block.
19597     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19598     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19599     MBB->addSuccessor(EndMBB);
19600   }
19601
19602   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19603   // that was just emitted, but clearly shouldn't be "saved".
19604   assert((MI->getNumOperands() <= 3 ||
19605           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19606           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19607          && "Expected last argument to be EFLAGS");
19608   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19609   // In the XMM save block, save all the XMM argument registers.
19610   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19611     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19612     MachineMemOperand *MMO =
19613       F->getMachineMemOperand(
19614           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19615         MachineMemOperand::MOStore,
19616         /*Size=*/16, /*Align=*/16);
19617     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19618       .addFrameIndex(RegSaveFrameIndex)
19619       .addImm(/*Scale=*/1)
19620       .addReg(/*IndexReg=*/0)
19621       .addImm(/*Disp=*/Offset)
19622       .addReg(/*Segment=*/0)
19623       .addReg(MI->getOperand(i).getReg())
19624       .addMemOperand(MMO);
19625   }
19626
19627   MI->eraseFromParent();   // The pseudo instruction is gone now.
19628
19629   return EndMBB;
19630 }
19631
19632 // The EFLAGS operand of SelectItr might be missing a kill marker
19633 // because there were multiple uses of EFLAGS, and ISel didn't know
19634 // which to mark. Figure out whether SelectItr should have had a
19635 // kill marker, and set it if it should. Returns the correct kill
19636 // marker value.
19637 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19638                                      MachineBasicBlock* BB,
19639                                      const TargetRegisterInfo* TRI) {
19640   // Scan forward through BB for a use/def of EFLAGS.
19641   MachineBasicBlock::iterator miI(std::next(SelectItr));
19642   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19643     const MachineInstr& mi = *miI;
19644     if (mi.readsRegister(X86::EFLAGS))
19645       return false;
19646     if (mi.definesRegister(X86::EFLAGS))
19647       break; // Should have kill-flag - update below.
19648   }
19649
19650   // If we hit the end of the block, check whether EFLAGS is live into a
19651   // successor.
19652   if (miI == BB->end()) {
19653     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19654                                           sEnd = BB->succ_end();
19655          sItr != sEnd; ++sItr) {
19656       MachineBasicBlock* succ = *sItr;
19657       if (succ->isLiveIn(X86::EFLAGS))
19658         return false;
19659     }
19660   }
19661
19662   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19663   // out. SelectMI should have a kill flag on EFLAGS.
19664   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19665   return true;
19666 }
19667
19668 MachineBasicBlock *
19669 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19670                                      MachineBasicBlock *BB) const {
19671   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19672   DebugLoc DL = MI->getDebugLoc();
19673
19674   // To "insert" a SELECT_CC instruction, we actually have to insert the
19675   // diamond control-flow pattern.  The incoming instruction knows the
19676   // destination vreg to set, the condition code register to branch on, the
19677   // true/false values to select between, and a branch opcode to use.
19678   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19679   MachineFunction::iterator It = BB;
19680   ++It;
19681
19682   //  thisMBB:
19683   //  ...
19684   //   TrueVal = ...
19685   //   cmpTY ccX, r1, r2
19686   //   bCC copy1MBB
19687   //   fallthrough --> copy0MBB
19688   MachineBasicBlock *thisMBB = BB;
19689   MachineFunction *F = BB->getParent();
19690
19691   // We also lower double CMOVs:
19692   //   (CMOV (CMOV F, T, cc1), T, cc2)
19693   // to two successives branches.  For that, we look for another CMOV as the
19694   // following instruction.
19695   //
19696   // Without this, we would add a PHI between the two jumps, which ends up
19697   // creating a few copies all around. For instance, for
19698   //
19699   //    (sitofp (zext (fcmp une)))
19700   //
19701   // we would generate:
19702   //
19703   //         ucomiss %xmm1, %xmm0
19704   //         movss  <1.0f>, %xmm0
19705   //         movaps  %xmm0, %xmm1
19706   //         jne     .LBB5_2
19707   //         xorps   %xmm1, %xmm1
19708   // .LBB5_2:
19709   //         jp      .LBB5_4
19710   //         movaps  %xmm1, %xmm0
19711   // .LBB5_4:
19712   //         retq
19713   //
19714   // because this custom-inserter would have generated:
19715   //
19716   //   A
19717   //   | \
19718   //   |  B
19719   //   | /
19720   //   C
19721   //   | \
19722   //   |  D
19723   //   | /
19724   //   E
19725   //
19726   // A: X = ...; Y = ...
19727   // B: empty
19728   // C: Z = PHI [X, A], [Y, B]
19729   // D: empty
19730   // E: PHI [X, C], [Z, D]
19731   //
19732   // If we lower both CMOVs in a single step, we can instead generate:
19733   //
19734   //   A
19735   //   | \
19736   //   |  C
19737   //   | /|
19738   //   |/ |
19739   //   |  |
19740   //   |  D
19741   //   | /
19742   //   E
19743   //
19744   // A: X = ...; Y = ...
19745   // D: empty
19746   // E: PHI [X, A], [X, C], [Y, D]
19747   //
19748   // Which, in our sitofp/fcmp example, gives us something like:
19749   //
19750   //         ucomiss %xmm1, %xmm0
19751   //         movss  <1.0f>, %xmm0
19752   //         jne     .LBB5_4
19753   //         jp      .LBB5_4
19754   //         xorps   %xmm0, %xmm0
19755   // .LBB5_4:
19756   //         retq
19757   //
19758   MachineInstr *NextCMOV = nullptr;
19759   MachineBasicBlock::iterator NextMIIt =
19760       std::next(MachineBasicBlock::iterator(MI));
19761   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19762       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19763       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19764     NextCMOV = &*NextMIIt;
19765
19766   MachineBasicBlock *jcc1MBB = nullptr;
19767
19768   // If we have a double CMOV, we lower it to two successive branches to
19769   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19770   if (NextCMOV) {
19771     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19772     F->insert(It, jcc1MBB);
19773     jcc1MBB->addLiveIn(X86::EFLAGS);
19774   }
19775
19776   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19777   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19778   F->insert(It, copy0MBB);
19779   F->insert(It, sinkMBB);
19780
19781   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19782   // live into the sink and copy blocks.
19783   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19784
19785   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19786   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19787       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19788     copy0MBB->addLiveIn(X86::EFLAGS);
19789     sinkMBB->addLiveIn(X86::EFLAGS);
19790   }
19791
19792   // Transfer the remainder of BB and its successor edges to sinkMBB.
19793   sinkMBB->splice(sinkMBB->begin(), BB,
19794                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19795   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19796
19797   // Add the true and fallthrough blocks as its successors.
19798   if (NextCMOV) {
19799     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19800     BB->addSuccessor(jcc1MBB);
19801
19802     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19803     // jump to the sinkMBB.
19804     jcc1MBB->addSuccessor(copy0MBB);
19805     jcc1MBB->addSuccessor(sinkMBB);
19806   } else {
19807     BB->addSuccessor(copy0MBB);
19808   }
19809
19810   // The true block target of the first (or only) branch is always sinkMBB.
19811   BB->addSuccessor(sinkMBB);
19812
19813   // Create the conditional branch instruction.
19814   unsigned Opc =
19815     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19816   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19817
19818   if (NextCMOV) {
19819     unsigned Opc2 = X86::GetCondBranchFromCond(
19820         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19821     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19822   }
19823
19824   //  copy0MBB:
19825   //   %FalseValue = ...
19826   //   # fallthrough to sinkMBB
19827   copy0MBB->addSuccessor(sinkMBB);
19828
19829   //  sinkMBB:
19830   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19831   //  ...
19832   MachineInstrBuilder MIB =
19833       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19834               MI->getOperand(0).getReg())
19835           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19836           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19837
19838   // If we have a double CMOV, the second Jcc provides the same incoming
19839   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19840   if (NextCMOV) {
19841     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19842     // Copy the PHI result to the register defined by the second CMOV.
19843     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19844             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19845         .addReg(MI->getOperand(0).getReg());
19846     NextCMOV->eraseFromParent();
19847   }
19848
19849   MI->eraseFromParent();   // The pseudo instruction is gone now.
19850   return sinkMBB;
19851 }
19852
19853 MachineBasicBlock *
19854 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19855                                         MachineBasicBlock *BB) const {
19856   MachineFunction *MF = BB->getParent();
19857   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19858   DebugLoc DL = MI->getDebugLoc();
19859   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19860
19861   assert(MF->shouldSplitStack());
19862
19863   const bool Is64Bit = Subtarget->is64Bit();
19864   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19865
19866   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19867   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19868
19869   // BB:
19870   //  ... [Till the alloca]
19871   // If stacklet is not large enough, jump to mallocMBB
19872   //
19873   // bumpMBB:
19874   //  Allocate by subtracting from RSP
19875   //  Jump to continueMBB
19876   //
19877   // mallocMBB:
19878   //  Allocate by call to runtime
19879   //
19880   // continueMBB:
19881   //  ...
19882   //  [rest of original BB]
19883   //
19884
19885   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19886   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19887   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19888
19889   MachineRegisterInfo &MRI = MF->getRegInfo();
19890   const TargetRegisterClass *AddrRegClass =
19891     getRegClassFor(getPointerTy());
19892
19893   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19894     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19895     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19896     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19897     sizeVReg = MI->getOperand(1).getReg(),
19898     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19899
19900   MachineFunction::iterator MBBIter = BB;
19901   ++MBBIter;
19902
19903   MF->insert(MBBIter, bumpMBB);
19904   MF->insert(MBBIter, mallocMBB);
19905   MF->insert(MBBIter, continueMBB);
19906
19907   continueMBB->splice(continueMBB->begin(), BB,
19908                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19909   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19910
19911   // Add code to the main basic block to check if the stack limit has been hit,
19912   // and if so, jump to mallocMBB otherwise to bumpMBB.
19913   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19914   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19915     .addReg(tmpSPVReg).addReg(sizeVReg);
19916   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19917     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19918     .addReg(SPLimitVReg);
19919   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19920
19921   // bumpMBB simply decreases the stack pointer, since we know the current
19922   // stacklet has enough space.
19923   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19924     .addReg(SPLimitVReg);
19925   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19926     .addReg(SPLimitVReg);
19927   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19928
19929   // Calls into a routine in libgcc to allocate more space from the heap.
19930   const uint32_t *RegMask =
19931       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19932   if (IsLP64) {
19933     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19934       .addReg(sizeVReg);
19935     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19936       .addExternalSymbol("__morestack_allocate_stack_space")
19937       .addRegMask(RegMask)
19938       .addReg(X86::RDI, RegState::Implicit)
19939       .addReg(X86::RAX, RegState::ImplicitDefine);
19940   } else if (Is64Bit) {
19941     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19942       .addReg(sizeVReg);
19943     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19944       .addExternalSymbol("__morestack_allocate_stack_space")
19945       .addRegMask(RegMask)
19946       .addReg(X86::EDI, RegState::Implicit)
19947       .addReg(X86::EAX, RegState::ImplicitDefine);
19948   } else {
19949     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19950       .addImm(12);
19951     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19952     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19953       .addExternalSymbol("__morestack_allocate_stack_space")
19954       .addRegMask(RegMask)
19955       .addReg(X86::EAX, RegState::ImplicitDefine);
19956   }
19957
19958   if (!Is64Bit)
19959     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19960       .addImm(16);
19961
19962   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19963     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19964   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19965
19966   // Set up the CFG correctly.
19967   BB->addSuccessor(bumpMBB);
19968   BB->addSuccessor(mallocMBB);
19969   mallocMBB->addSuccessor(continueMBB);
19970   bumpMBB->addSuccessor(continueMBB);
19971
19972   // Take care of the PHI nodes.
19973   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19974           MI->getOperand(0).getReg())
19975     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19976     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19977
19978   // Delete the original pseudo instruction.
19979   MI->eraseFromParent();
19980
19981   // And we're done.
19982   return continueMBB;
19983 }
19984
19985 MachineBasicBlock *
19986 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19987                                         MachineBasicBlock *BB) const {
19988   DebugLoc DL = MI->getDebugLoc();
19989
19990   assert(!Subtarget->isTargetMachO());
19991
19992   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
19993                                                     DL);
19994
19995   MI->eraseFromParent();   // The pseudo instruction is gone now.
19996   return BB;
19997 }
19998
19999 MachineBasicBlock *
20000 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20001                                       MachineBasicBlock *BB) const {
20002   // This is pretty easy.  We're taking the value that we received from
20003   // our load from the relocation, sticking it in either RDI (x86-64)
20004   // or EAX and doing an indirect call.  The return value will then
20005   // be in the normal return register.
20006   MachineFunction *F = BB->getParent();
20007   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20008   DebugLoc DL = MI->getDebugLoc();
20009
20010   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20011   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20012
20013   // Get a register mask for the lowered call.
20014   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20015   // proper register mask.
20016   const uint32_t *RegMask =
20017       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20018   if (Subtarget->is64Bit()) {
20019     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20020                                       TII->get(X86::MOV64rm), X86::RDI)
20021     .addReg(X86::RIP)
20022     .addImm(0).addReg(0)
20023     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20024                       MI->getOperand(3).getTargetFlags())
20025     .addReg(0);
20026     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20027     addDirectMem(MIB, X86::RDI);
20028     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20029   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20030     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20031                                       TII->get(X86::MOV32rm), X86::EAX)
20032     .addReg(0)
20033     .addImm(0).addReg(0)
20034     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20035                       MI->getOperand(3).getTargetFlags())
20036     .addReg(0);
20037     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20038     addDirectMem(MIB, X86::EAX);
20039     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20040   } else {
20041     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20042                                       TII->get(X86::MOV32rm), X86::EAX)
20043     .addReg(TII->getGlobalBaseReg(F))
20044     .addImm(0).addReg(0)
20045     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20046                       MI->getOperand(3).getTargetFlags())
20047     .addReg(0);
20048     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20049     addDirectMem(MIB, X86::EAX);
20050     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20051   }
20052
20053   MI->eraseFromParent(); // The pseudo instruction is gone now.
20054   return BB;
20055 }
20056
20057 MachineBasicBlock *
20058 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20059                                     MachineBasicBlock *MBB) const {
20060   DebugLoc DL = MI->getDebugLoc();
20061   MachineFunction *MF = MBB->getParent();
20062   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20063   MachineRegisterInfo &MRI = MF->getRegInfo();
20064
20065   const BasicBlock *BB = MBB->getBasicBlock();
20066   MachineFunction::iterator I = MBB;
20067   ++I;
20068
20069   // Memory Reference
20070   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20071   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20072
20073   unsigned DstReg;
20074   unsigned MemOpndSlot = 0;
20075
20076   unsigned CurOp = 0;
20077
20078   DstReg = MI->getOperand(CurOp++).getReg();
20079   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20080   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20081   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20082   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20083
20084   MemOpndSlot = CurOp;
20085
20086   MVT PVT = getPointerTy();
20087   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20088          "Invalid Pointer Size!");
20089
20090   // For v = setjmp(buf), we generate
20091   //
20092   // thisMBB:
20093   //  buf[LabelOffset] = restoreMBB
20094   //  SjLjSetup restoreMBB
20095   //
20096   // mainMBB:
20097   //  v_main = 0
20098   //
20099   // sinkMBB:
20100   //  v = phi(main, restore)
20101   //
20102   // restoreMBB:
20103   //  if base pointer being used, load it from frame
20104   //  v_restore = 1
20105
20106   MachineBasicBlock *thisMBB = MBB;
20107   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20108   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20109   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20110   MF->insert(I, mainMBB);
20111   MF->insert(I, sinkMBB);
20112   MF->push_back(restoreMBB);
20113
20114   MachineInstrBuilder MIB;
20115
20116   // Transfer the remainder of BB and its successor edges to sinkMBB.
20117   sinkMBB->splice(sinkMBB->begin(), MBB,
20118                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20119   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20120
20121   // thisMBB:
20122   unsigned PtrStoreOpc = 0;
20123   unsigned LabelReg = 0;
20124   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20125   Reloc::Model RM = MF->getTarget().getRelocationModel();
20126   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20127                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20128
20129   // Prepare IP either in reg or imm.
20130   if (!UseImmLabel) {
20131     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20132     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20133     LabelReg = MRI.createVirtualRegister(PtrRC);
20134     if (Subtarget->is64Bit()) {
20135       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20136               .addReg(X86::RIP)
20137               .addImm(0)
20138               .addReg(0)
20139               .addMBB(restoreMBB)
20140               .addReg(0);
20141     } else {
20142       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20143       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20144               .addReg(XII->getGlobalBaseReg(MF))
20145               .addImm(0)
20146               .addReg(0)
20147               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20148               .addReg(0);
20149     }
20150   } else
20151     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20152   // Store IP
20153   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20154   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20155     if (i == X86::AddrDisp)
20156       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20157     else
20158       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20159   }
20160   if (!UseImmLabel)
20161     MIB.addReg(LabelReg);
20162   else
20163     MIB.addMBB(restoreMBB);
20164   MIB.setMemRefs(MMOBegin, MMOEnd);
20165   // Setup
20166   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20167           .addMBB(restoreMBB);
20168
20169   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20170   MIB.addRegMask(RegInfo->getNoPreservedMask());
20171   thisMBB->addSuccessor(mainMBB);
20172   thisMBB->addSuccessor(restoreMBB);
20173
20174   // mainMBB:
20175   //  EAX = 0
20176   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20177   mainMBB->addSuccessor(sinkMBB);
20178
20179   // sinkMBB:
20180   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20181           TII->get(X86::PHI), DstReg)
20182     .addReg(mainDstReg).addMBB(mainMBB)
20183     .addReg(restoreDstReg).addMBB(restoreMBB);
20184
20185   // restoreMBB:
20186   if (RegInfo->hasBasePointer(*MF)) {
20187     const bool Uses64BitFramePtr =
20188         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20189     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20190     X86FI->setRestoreBasePointer(MF);
20191     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20192     unsigned BasePtr = RegInfo->getBaseRegister();
20193     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20194     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20195                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20196       .setMIFlag(MachineInstr::FrameSetup);
20197   }
20198   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20199   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20200   restoreMBB->addSuccessor(sinkMBB);
20201
20202   MI->eraseFromParent();
20203   return sinkMBB;
20204 }
20205
20206 MachineBasicBlock *
20207 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20208                                      MachineBasicBlock *MBB) const {
20209   DebugLoc DL = MI->getDebugLoc();
20210   MachineFunction *MF = MBB->getParent();
20211   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20212   MachineRegisterInfo &MRI = MF->getRegInfo();
20213
20214   // Memory Reference
20215   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20216   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20217
20218   MVT PVT = getPointerTy();
20219   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20220          "Invalid Pointer Size!");
20221
20222   const TargetRegisterClass *RC =
20223     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20224   unsigned Tmp = MRI.createVirtualRegister(RC);
20225   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20226   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20227   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20228   unsigned SP = RegInfo->getStackRegister();
20229
20230   MachineInstrBuilder MIB;
20231
20232   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20233   const int64_t SPOffset = 2 * PVT.getStoreSize();
20234
20235   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20236   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20237
20238   // Reload FP
20239   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20240   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20241     MIB.addOperand(MI->getOperand(i));
20242   MIB.setMemRefs(MMOBegin, MMOEnd);
20243   // Reload IP
20244   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20245   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20246     if (i == X86::AddrDisp)
20247       MIB.addDisp(MI->getOperand(i), LabelOffset);
20248     else
20249       MIB.addOperand(MI->getOperand(i));
20250   }
20251   MIB.setMemRefs(MMOBegin, MMOEnd);
20252   // Reload SP
20253   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20254   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20255     if (i == X86::AddrDisp)
20256       MIB.addDisp(MI->getOperand(i), SPOffset);
20257     else
20258       MIB.addOperand(MI->getOperand(i));
20259   }
20260   MIB.setMemRefs(MMOBegin, MMOEnd);
20261   // Jump
20262   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20263
20264   MI->eraseFromParent();
20265   return MBB;
20266 }
20267
20268 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20269 // accumulator loops. Writing back to the accumulator allows the coalescer
20270 // to remove extra copies in the loop.
20271 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20272 MachineBasicBlock *
20273 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20274                                  MachineBasicBlock *MBB) const {
20275   MachineOperand &AddendOp = MI->getOperand(3);
20276
20277   // Bail out early if the addend isn't a register - we can't switch these.
20278   if (!AddendOp.isReg())
20279     return MBB;
20280
20281   MachineFunction &MF = *MBB->getParent();
20282   MachineRegisterInfo &MRI = MF.getRegInfo();
20283
20284   // Check whether the addend is defined by a PHI:
20285   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20286   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20287   if (!AddendDef.isPHI())
20288     return MBB;
20289
20290   // Look for the following pattern:
20291   // loop:
20292   //   %addend = phi [%entry, 0], [%loop, %result]
20293   //   ...
20294   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20295
20296   // Replace with:
20297   //   loop:
20298   //   %addend = phi [%entry, 0], [%loop, %result]
20299   //   ...
20300   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20301
20302   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20303     assert(AddendDef.getOperand(i).isReg());
20304     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20305     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20306     if (&PHISrcInst == MI) {
20307       // Found a matching instruction.
20308       unsigned NewFMAOpc = 0;
20309       switch (MI->getOpcode()) {
20310         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20311         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20312         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20313         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20314         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20315         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20316         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20317         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20318         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20319         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20320         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20321         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20322         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20323         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20324         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20325         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20326         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20327         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20328         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20329         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20330
20331         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20332         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20333         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20334         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20335         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20336         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20337         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20338         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20339         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20340         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20341         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20342         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20343         default: llvm_unreachable("Unrecognized FMA variant.");
20344       }
20345
20346       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20347       MachineInstrBuilder MIB =
20348         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20349         .addOperand(MI->getOperand(0))
20350         .addOperand(MI->getOperand(3))
20351         .addOperand(MI->getOperand(2))
20352         .addOperand(MI->getOperand(1));
20353       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20354       MI->eraseFromParent();
20355     }
20356   }
20357
20358   return MBB;
20359 }
20360
20361 MachineBasicBlock *
20362 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20363                                                MachineBasicBlock *BB) const {
20364   switch (MI->getOpcode()) {
20365   default: llvm_unreachable("Unexpected instr type to insert");
20366   case X86::TAILJMPd64:
20367   case X86::TAILJMPr64:
20368   case X86::TAILJMPm64:
20369   case X86::TAILJMPd64_REX:
20370   case X86::TAILJMPr64_REX:
20371   case X86::TAILJMPm64_REX:
20372     llvm_unreachable("TAILJMP64 would not be touched here.");
20373   case X86::TCRETURNdi64:
20374   case X86::TCRETURNri64:
20375   case X86::TCRETURNmi64:
20376     return BB;
20377   case X86::WIN_ALLOCA:
20378     return EmitLoweredWinAlloca(MI, BB);
20379   case X86::SEG_ALLOCA_32:
20380   case X86::SEG_ALLOCA_64:
20381     return EmitLoweredSegAlloca(MI, BB);
20382   case X86::TLSCall_32:
20383   case X86::TLSCall_64:
20384     return EmitLoweredTLSCall(MI, BB);
20385   case X86::CMOV_GR8:
20386   case X86::CMOV_FR32:
20387   case X86::CMOV_FR64:
20388   case X86::CMOV_V4F32:
20389   case X86::CMOV_V2F64:
20390   case X86::CMOV_V2I64:
20391   case X86::CMOV_V8F32:
20392   case X86::CMOV_V4F64:
20393   case X86::CMOV_V4I64:
20394   case X86::CMOV_V16F32:
20395   case X86::CMOV_V8F64:
20396   case X86::CMOV_V8I64:
20397   case X86::CMOV_GR16:
20398   case X86::CMOV_GR32:
20399   case X86::CMOV_RFP32:
20400   case X86::CMOV_RFP64:
20401   case X86::CMOV_RFP80:
20402   case X86::CMOV_V8I1:
20403   case X86::CMOV_V16I1:
20404   case X86::CMOV_V32I1:
20405   case X86::CMOV_V64I1:
20406     return EmitLoweredSelect(MI, BB);
20407
20408   case X86::FP32_TO_INT16_IN_MEM:
20409   case X86::FP32_TO_INT32_IN_MEM:
20410   case X86::FP32_TO_INT64_IN_MEM:
20411   case X86::FP64_TO_INT16_IN_MEM:
20412   case X86::FP64_TO_INT32_IN_MEM:
20413   case X86::FP64_TO_INT64_IN_MEM:
20414   case X86::FP80_TO_INT16_IN_MEM:
20415   case X86::FP80_TO_INT32_IN_MEM:
20416   case X86::FP80_TO_INT64_IN_MEM: {
20417     MachineFunction *F = BB->getParent();
20418     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20419     DebugLoc DL = MI->getDebugLoc();
20420
20421     // Change the floating point control register to use "round towards zero"
20422     // mode when truncating to an integer value.
20423     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20424     addFrameReference(BuildMI(*BB, MI, DL,
20425                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20426
20427     // Load the old value of the high byte of the control word...
20428     unsigned OldCW =
20429       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20430     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20431                       CWFrameIdx);
20432
20433     // Set the high part to be round to zero...
20434     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20435       .addImm(0xC7F);
20436
20437     // Reload the modified control word now...
20438     addFrameReference(BuildMI(*BB, MI, DL,
20439                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20440
20441     // Restore the memory image of control word to original value
20442     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20443       .addReg(OldCW);
20444
20445     // Get the X86 opcode to use.
20446     unsigned Opc;
20447     switch (MI->getOpcode()) {
20448     default: llvm_unreachable("illegal opcode!");
20449     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20450     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20451     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20452     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20453     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20454     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20455     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20456     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20457     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20458     }
20459
20460     X86AddressMode AM;
20461     MachineOperand &Op = MI->getOperand(0);
20462     if (Op.isReg()) {
20463       AM.BaseType = X86AddressMode::RegBase;
20464       AM.Base.Reg = Op.getReg();
20465     } else {
20466       AM.BaseType = X86AddressMode::FrameIndexBase;
20467       AM.Base.FrameIndex = Op.getIndex();
20468     }
20469     Op = MI->getOperand(1);
20470     if (Op.isImm())
20471       AM.Scale = Op.getImm();
20472     Op = MI->getOperand(2);
20473     if (Op.isImm())
20474       AM.IndexReg = Op.getImm();
20475     Op = MI->getOperand(3);
20476     if (Op.isGlobal()) {
20477       AM.GV = Op.getGlobal();
20478     } else {
20479       AM.Disp = Op.getImm();
20480     }
20481     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20482                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20483
20484     // Reload the original control word now.
20485     addFrameReference(BuildMI(*BB, MI, DL,
20486                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20487
20488     MI->eraseFromParent();   // The pseudo instruction is gone now.
20489     return BB;
20490   }
20491     // String/text processing lowering.
20492   case X86::PCMPISTRM128REG:
20493   case X86::VPCMPISTRM128REG:
20494   case X86::PCMPISTRM128MEM:
20495   case X86::VPCMPISTRM128MEM:
20496   case X86::PCMPESTRM128REG:
20497   case X86::VPCMPESTRM128REG:
20498   case X86::PCMPESTRM128MEM:
20499   case X86::VPCMPESTRM128MEM:
20500     assert(Subtarget->hasSSE42() &&
20501            "Target must have SSE4.2 or AVX features enabled");
20502     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20503
20504   // String/text processing lowering.
20505   case X86::PCMPISTRIREG:
20506   case X86::VPCMPISTRIREG:
20507   case X86::PCMPISTRIMEM:
20508   case X86::VPCMPISTRIMEM:
20509   case X86::PCMPESTRIREG:
20510   case X86::VPCMPESTRIREG:
20511   case X86::PCMPESTRIMEM:
20512   case X86::VPCMPESTRIMEM:
20513     assert(Subtarget->hasSSE42() &&
20514            "Target must have SSE4.2 or AVX features enabled");
20515     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20516
20517   // Thread synchronization.
20518   case X86::MONITOR:
20519     return EmitMonitor(MI, BB, Subtarget);
20520
20521   // xbegin
20522   case X86::XBEGIN:
20523     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20524
20525   case X86::VASTART_SAVE_XMM_REGS:
20526     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20527
20528   case X86::VAARG_64:
20529     return EmitVAARG64WithCustomInserter(MI, BB);
20530
20531   case X86::EH_SjLj_SetJmp32:
20532   case X86::EH_SjLj_SetJmp64:
20533     return emitEHSjLjSetJmp(MI, BB);
20534
20535   case X86::EH_SjLj_LongJmp32:
20536   case X86::EH_SjLj_LongJmp64:
20537     return emitEHSjLjLongJmp(MI, BB);
20538
20539   case TargetOpcode::STATEPOINT:
20540     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20541     // this point in the process.  We diverge later.
20542     return emitPatchPoint(MI, BB);
20543
20544   case TargetOpcode::STACKMAP:
20545   case TargetOpcode::PATCHPOINT:
20546     return emitPatchPoint(MI, BB);
20547
20548   case X86::VFMADDPDr213r:
20549   case X86::VFMADDPSr213r:
20550   case X86::VFMADDSDr213r:
20551   case X86::VFMADDSSr213r:
20552   case X86::VFMSUBPDr213r:
20553   case X86::VFMSUBPSr213r:
20554   case X86::VFMSUBSDr213r:
20555   case X86::VFMSUBSSr213r:
20556   case X86::VFNMADDPDr213r:
20557   case X86::VFNMADDPSr213r:
20558   case X86::VFNMADDSDr213r:
20559   case X86::VFNMADDSSr213r:
20560   case X86::VFNMSUBPDr213r:
20561   case X86::VFNMSUBPSr213r:
20562   case X86::VFNMSUBSDr213r:
20563   case X86::VFNMSUBSSr213r:
20564   case X86::VFMADDSUBPDr213r:
20565   case X86::VFMADDSUBPSr213r:
20566   case X86::VFMSUBADDPDr213r:
20567   case X86::VFMSUBADDPSr213r:
20568   case X86::VFMADDPDr213rY:
20569   case X86::VFMADDPSr213rY:
20570   case X86::VFMSUBPDr213rY:
20571   case X86::VFMSUBPSr213rY:
20572   case X86::VFNMADDPDr213rY:
20573   case X86::VFNMADDPSr213rY:
20574   case X86::VFNMSUBPDr213rY:
20575   case X86::VFNMSUBPSr213rY:
20576   case X86::VFMADDSUBPDr213rY:
20577   case X86::VFMADDSUBPSr213rY:
20578   case X86::VFMSUBADDPDr213rY:
20579   case X86::VFMSUBADDPSr213rY:
20580     return emitFMA3Instr(MI, BB);
20581   }
20582 }
20583
20584 //===----------------------------------------------------------------------===//
20585 //                           X86 Optimization Hooks
20586 //===----------------------------------------------------------------------===//
20587
20588 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20589                                                       APInt &KnownZero,
20590                                                       APInt &KnownOne,
20591                                                       const SelectionDAG &DAG,
20592                                                       unsigned Depth) const {
20593   unsigned BitWidth = KnownZero.getBitWidth();
20594   unsigned Opc = Op.getOpcode();
20595   assert((Opc >= ISD::BUILTIN_OP_END ||
20596           Opc == ISD::INTRINSIC_WO_CHAIN ||
20597           Opc == ISD::INTRINSIC_W_CHAIN ||
20598           Opc == ISD::INTRINSIC_VOID) &&
20599          "Should use MaskedValueIsZero if you don't know whether Op"
20600          " is a target node!");
20601
20602   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20603   switch (Opc) {
20604   default: break;
20605   case X86ISD::ADD:
20606   case X86ISD::SUB:
20607   case X86ISD::ADC:
20608   case X86ISD::SBB:
20609   case X86ISD::SMUL:
20610   case X86ISD::UMUL:
20611   case X86ISD::INC:
20612   case X86ISD::DEC:
20613   case X86ISD::OR:
20614   case X86ISD::XOR:
20615   case X86ISD::AND:
20616     // These nodes' second result is a boolean.
20617     if (Op.getResNo() == 0)
20618       break;
20619     // Fallthrough
20620   case X86ISD::SETCC:
20621     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20622     break;
20623   case ISD::INTRINSIC_WO_CHAIN: {
20624     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20625     unsigned NumLoBits = 0;
20626     switch (IntId) {
20627     default: break;
20628     case Intrinsic::x86_sse_movmsk_ps:
20629     case Intrinsic::x86_avx_movmsk_ps_256:
20630     case Intrinsic::x86_sse2_movmsk_pd:
20631     case Intrinsic::x86_avx_movmsk_pd_256:
20632     case Intrinsic::x86_mmx_pmovmskb:
20633     case Intrinsic::x86_sse2_pmovmskb_128:
20634     case Intrinsic::x86_avx2_pmovmskb: {
20635       // High bits of movmskp{s|d}, pmovmskb are known zero.
20636       switch (IntId) {
20637         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20638         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20639         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20640         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20641         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20642         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20643         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20644         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20645       }
20646       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20647       break;
20648     }
20649     }
20650     break;
20651   }
20652   }
20653 }
20654
20655 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20656   SDValue Op,
20657   const SelectionDAG &,
20658   unsigned Depth) const {
20659   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20660   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20661     return Op.getValueType().getScalarType().getSizeInBits();
20662
20663   // Fallback case.
20664   return 1;
20665 }
20666
20667 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20668 /// node is a GlobalAddress + offset.
20669 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20670                                        const GlobalValue* &GA,
20671                                        int64_t &Offset) const {
20672   if (N->getOpcode() == X86ISD::Wrapper) {
20673     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20674       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20675       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20676       return true;
20677     }
20678   }
20679   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20680 }
20681
20682 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20683 /// same as extracting the high 128-bit part of 256-bit vector and then
20684 /// inserting the result into the low part of a new 256-bit vector
20685 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20686   EVT VT = SVOp->getValueType(0);
20687   unsigned NumElems = VT.getVectorNumElements();
20688
20689   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20690   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20691     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20692         SVOp->getMaskElt(j) >= 0)
20693       return false;
20694
20695   return true;
20696 }
20697
20698 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20699 /// same as extracting the low 128-bit part of 256-bit vector and then
20700 /// inserting the result into the high part of a new 256-bit vector
20701 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20702   EVT VT = SVOp->getValueType(0);
20703   unsigned NumElems = VT.getVectorNumElements();
20704
20705   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20706   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20707     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20708         SVOp->getMaskElt(j) >= 0)
20709       return false;
20710
20711   return true;
20712 }
20713
20714 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20715 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20716                                         TargetLowering::DAGCombinerInfo &DCI,
20717                                         const X86Subtarget* Subtarget) {
20718   SDLoc dl(N);
20719   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20720   SDValue V1 = SVOp->getOperand(0);
20721   SDValue V2 = SVOp->getOperand(1);
20722   EVT VT = SVOp->getValueType(0);
20723   unsigned NumElems = VT.getVectorNumElements();
20724
20725   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20726       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20727     //
20728     //                   0,0,0,...
20729     //                      |
20730     //    V      UNDEF    BUILD_VECTOR    UNDEF
20731     //     \      /           \           /
20732     //  CONCAT_VECTOR         CONCAT_VECTOR
20733     //         \                  /
20734     //          \                /
20735     //          RESULT: V + zero extended
20736     //
20737     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20738         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20739         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20740       return SDValue();
20741
20742     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20743       return SDValue();
20744
20745     // To match the shuffle mask, the first half of the mask should
20746     // be exactly the first vector, and all the rest a splat with the
20747     // first element of the second one.
20748     for (unsigned i = 0; i != NumElems/2; ++i)
20749       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20750           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20751         return SDValue();
20752
20753     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20754     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20755       if (Ld->hasNUsesOfValue(1, 0)) {
20756         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20757         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20758         SDValue ResNode =
20759           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20760                                   Ld->getMemoryVT(),
20761                                   Ld->getPointerInfo(),
20762                                   Ld->getAlignment(),
20763                                   false/*isVolatile*/, true/*ReadMem*/,
20764                                   false/*WriteMem*/);
20765
20766         // Make sure the newly-created LOAD is in the same position as Ld in
20767         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20768         // and update uses of Ld's output chain to use the TokenFactor.
20769         if (Ld->hasAnyUseOfValue(1)) {
20770           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20771                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20772           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20773           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20774                                  SDValue(ResNode.getNode(), 1));
20775         }
20776
20777         return DAG.getBitcast(VT, ResNode);
20778       }
20779     }
20780
20781     // Emit a zeroed vector and insert the desired subvector on its
20782     // first half.
20783     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20784     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20785     return DCI.CombineTo(N, InsV);
20786   }
20787
20788   //===--------------------------------------------------------------------===//
20789   // Combine some shuffles into subvector extracts and inserts:
20790   //
20791
20792   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20793   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20794     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20795     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20796     return DCI.CombineTo(N, InsV);
20797   }
20798
20799   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20800   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20801     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20802     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20803     return DCI.CombineTo(N, InsV);
20804   }
20805
20806   return SDValue();
20807 }
20808
20809 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20810 /// possible.
20811 ///
20812 /// This is the leaf of the recursive combinine below. When we have found some
20813 /// chain of single-use x86 shuffle instructions and accumulated the combined
20814 /// shuffle mask represented by them, this will try to pattern match that mask
20815 /// into either a single instruction if there is a special purpose instruction
20816 /// for this operation, or into a PSHUFB instruction which is a fully general
20817 /// instruction but should only be used to replace chains over a certain depth.
20818 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20819                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20820                                    TargetLowering::DAGCombinerInfo &DCI,
20821                                    const X86Subtarget *Subtarget) {
20822   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20823
20824   // Find the operand that enters the chain. Note that multiple uses are OK
20825   // here, we're not going to remove the operand we find.
20826   SDValue Input = Op.getOperand(0);
20827   while (Input.getOpcode() == ISD::BITCAST)
20828     Input = Input.getOperand(0);
20829
20830   MVT VT = Input.getSimpleValueType();
20831   MVT RootVT = Root.getSimpleValueType();
20832   SDLoc DL(Root);
20833
20834   // Just remove no-op shuffle masks.
20835   if (Mask.size() == 1) {
20836     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20837                   /*AddTo*/ true);
20838     return true;
20839   }
20840
20841   // Use the float domain if the operand type is a floating point type.
20842   bool FloatDomain = VT.isFloatingPoint();
20843
20844   // For floating point shuffles, we don't have free copies in the shuffle
20845   // instructions or the ability to load as part of the instruction, so
20846   // canonicalize their shuffles to UNPCK or MOV variants.
20847   //
20848   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20849   // vectors because it can have a load folded into it that UNPCK cannot. This
20850   // doesn't preclude something switching to the shorter encoding post-RA.
20851   //
20852   // FIXME: Should teach these routines about AVX vector widths.
20853   if (FloatDomain && VT.getSizeInBits() == 128) {
20854     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20855       bool Lo = Mask.equals({0, 0});
20856       unsigned Shuffle;
20857       MVT ShuffleVT;
20858       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20859       // is no slower than UNPCKLPD but has the option to fold the input operand
20860       // into even an unaligned memory load.
20861       if (Lo && Subtarget->hasSSE3()) {
20862         Shuffle = X86ISD::MOVDDUP;
20863         ShuffleVT = MVT::v2f64;
20864       } else {
20865         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20866         // than the UNPCK variants.
20867         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20868         ShuffleVT = MVT::v4f32;
20869       }
20870       if (Depth == 1 && Root->getOpcode() == Shuffle)
20871         return false; // Nothing to do!
20872       Op = DAG.getBitcast(ShuffleVT, Input);
20873       DCI.AddToWorklist(Op.getNode());
20874       if (Shuffle == X86ISD::MOVDDUP)
20875         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20876       else
20877         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20878       DCI.AddToWorklist(Op.getNode());
20879       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20880                     /*AddTo*/ true);
20881       return true;
20882     }
20883     if (Subtarget->hasSSE3() &&
20884         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20885       bool Lo = Mask.equals({0, 0, 2, 2});
20886       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20887       MVT ShuffleVT = MVT::v4f32;
20888       if (Depth == 1 && Root->getOpcode() == Shuffle)
20889         return false; // Nothing to do!
20890       Op = DAG.getBitcast(ShuffleVT, Input);
20891       DCI.AddToWorklist(Op.getNode());
20892       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20893       DCI.AddToWorklist(Op.getNode());
20894       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20895                     /*AddTo*/ true);
20896       return true;
20897     }
20898     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20899       bool Lo = Mask.equals({0, 0, 1, 1});
20900       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20901       MVT ShuffleVT = MVT::v4f32;
20902       if (Depth == 1 && Root->getOpcode() == Shuffle)
20903         return false; // Nothing to do!
20904       Op = DAG.getBitcast(ShuffleVT, Input);
20905       DCI.AddToWorklist(Op.getNode());
20906       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20907       DCI.AddToWorklist(Op.getNode());
20908       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20909                     /*AddTo*/ true);
20910       return true;
20911     }
20912   }
20913
20914   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20915   // variants as none of these have single-instruction variants that are
20916   // superior to the UNPCK formulation.
20917   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20918       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20919        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20920        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20921        Mask.equals(
20922            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20923     bool Lo = Mask[0] == 0;
20924     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20925     if (Depth == 1 && Root->getOpcode() == Shuffle)
20926       return false; // Nothing to do!
20927     MVT ShuffleVT;
20928     switch (Mask.size()) {
20929     case 8:
20930       ShuffleVT = MVT::v8i16;
20931       break;
20932     case 16:
20933       ShuffleVT = MVT::v16i8;
20934       break;
20935     default:
20936       llvm_unreachable("Impossible mask size!");
20937     };
20938     Op = DAG.getBitcast(ShuffleVT, Input);
20939     DCI.AddToWorklist(Op.getNode());
20940     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20941     DCI.AddToWorklist(Op.getNode());
20942     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20943                   /*AddTo*/ true);
20944     return true;
20945   }
20946
20947   // Don't try to re-form single instruction chains under any circumstances now
20948   // that we've done encoding canonicalization for them.
20949   if (Depth < 2)
20950     return false;
20951
20952   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20953   // can replace them with a single PSHUFB instruction profitably. Intel's
20954   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20955   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20956   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20957     SmallVector<SDValue, 16> PSHUFBMask;
20958     int NumBytes = VT.getSizeInBits() / 8;
20959     int Ratio = NumBytes / Mask.size();
20960     for (int i = 0; i < NumBytes; ++i) {
20961       if (Mask[i / Ratio] == SM_SentinelUndef) {
20962         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20963         continue;
20964       }
20965       int M = Mask[i / Ratio] != SM_SentinelZero
20966                   ? Ratio * Mask[i / Ratio] + i % Ratio
20967                   : 255;
20968       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20969     }
20970     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20971     Op = DAG.getBitcast(ByteVT, Input);
20972     DCI.AddToWorklist(Op.getNode());
20973     SDValue PSHUFBMaskOp =
20974         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20975     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20976     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20977     DCI.AddToWorklist(Op.getNode());
20978     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20979                   /*AddTo*/ true);
20980     return true;
20981   }
20982
20983   // Failed to find any combines.
20984   return false;
20985 }
20986
20987 /// \brief Fully generic combining of x86 shuffle instructions.
20988 ///
20989 /// This should be the last combine run over the x86 shuffle instructions. Once
20990 /// they have been fully optimized, this will recursively consider all chains
20991 /// of single-use shuffle instructions, build a generic model of the cumulative
20992 /// shuffle operation, and check for simpler instructions which implement this
20993 /// operation. We use this primarily for two purposes:
20994 ///
20995 /// 1) Collapse generic shuffles to specialized single instructions when
20996 ///    equivalent. In most cases, this is just an encoding size win, but
20997 ///    sometimes we will collapse multiple generic shuffles into a single
20998 ///    special-purpose shuffle.
20999 /// 2) Look for sequences of shuffle instructions with 3 or more total
21000 ///    instructions, and replace them with the slightly more expensive SSSE3
21001 ///    PSHUFB instruction if available. We do this as the last combining step
21002 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21003 ///    a suitable short sequence of other instructions. The PHUFB will either
21004 ///    use a register or have to read from memory and so is slightly (but only
21005 ///    slightly) more expensive than the other shuffle instructions.
21006 ///
21007 /// Because this is inherently a quadratic operation (for each shuffle in
21008 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21009 /// This should never be an issue in practice as the shuffle lowering doesn't
21010 /// produce sequences of more than 8 instructions.
21011 ///
21012 /// FIXME: We will currently miss some cases where the redundant shuffling
21013 /// would simplify under the threshold for PSHUFB formation because of
21014 /// combine-ordering. To fix this, we should do the redundant instruction
21015 /// combining in this recursive walk.
21016 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21017                                           ArrayRef<int> RootMask,
21018                                           int Depth, bool HasPSHUFB,
21019                                           SelectionDAG &DAG,
21020                                           TargetLowering::DAGCombinerInfo &DCI,
21021                                           const X86Subtarget *Subtarget) {
21022   // Bound the depth of our recursive combine because this is ultimately
21023   // quadratic in nature.
21024   if (Depth > 8)
21025     return false;
21026
21027   // Directly rip through bitcasts to find the underlying operand.
21028   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21029     Op = Op.getOperand(0);
21030
21031   MVT VT = Op.getSimpleValueType();
21032   if (!VT.isVector())
21033     return false; // Bail if we hit a non-vector.
21034
21035   assert(Root.getSimpleValueType().isVector() &&
21036          "Shuffles operate on vector types!");
21037   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21038          "Can only combine shuffles of the same vector register size.");
21039
21040   if (!isTargetShuffle(Op.getOpcode()))
21041     return false;
21042   SmallVector<int, 16> OpMask;
21043   bool IsUnary;
21044   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21045   // We only can combine unary shuffles which we can decode the mask for.
21046   if (!HaveMask || !IsUnary)
21047     return false;
21048
21049   assert(VT.getVectorNumElements() == OpMask.size() &&
21050          "Different mask size from vector size!");
21051   assert(((RootMask.size() > OpMask.size() &&
21052            RootMask.size() % OpMask.size() == 0) ||
21053           (OpMask.size() > RootMask.size() &&
21054            OpMask.size() % RootMask.size() == 0) ||
21055           OpMask.size() == RootMask.size()) &&
21056          "The smaller number of elements must divide the larger.");
21057   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21058   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21059   assert(((RootRatio == 1 && OpRatio == 1) ||
21060           (RootRatio == 1) != (OpRatio == 1)) &&
21061          "Must not have a ratio for both incoming and op masks!");
21062
21063   SmallVector<int, 16> Mask;
21064   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21065
21066   // Merge this shuffle operation's mask into our accumulated mask. Note that
21067   // this shuffle's mask will be the first applied to the input, followed by the
21068   // root mask to get us all the way to the root value arrangement. The reason
21069   // for this order is that we are recursing up the operation chain.
21070   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21071     int RootIdx = i / RootRatio;
21072     if (RootMask[RootIdx] < 0) {
21073       // This is a zero or undef lane, we're done.
21074       Mask.push_back(RootMask[RootIdx]);
21075       continue;
21076     }
21077
21078     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21079     int OpIdx = RootMaskedIdx / OpRatio;
21080     if (OpMask[OpIdx] < 0) {
21081       // The incoming lanes are zero or undef, it doesn't matter which ones we
21082       // are using.
21083       Mask.push_back(OpMask[OpIdx]);
21084       continue;
21085     }
21086
21087     // Ok, we have non-zero lanes, map them through.
21088     Mask.push_back(OpMask[OpIdx] * OpRatio +
21089                    RootMaskedIdx % OpRatio);
21090   }
21091
21092   // See if we can recurse into the operand to combine more things.
21093   switch (Op.getOpcode()) {
21094     case X86ISD::PSHUFB:
21095       HasPSHUFB = true;
21096     case X86ISD::PSHUFD:
21097     case X86ISD::PSHUFHW:
21098     case X86ISD::PSHUFLW:
21099       if (Op.getOperand(0).hasOneUse() &&
21100           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21101                                         HasPSHUFB, DAG, DCI, Subtarget))
21102         return true;
21103       break;
21104
21105     case X86ISD::UNPCKL:
21106     case X86ISD::UNPCKH:
21107       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21108       // We can't check for single use, we have to check that this shuffle is the only user.
21109       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21110           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21111                                         HasPSHUFB, DAG, DCI, Subtarget))
21112           return true;
21113       break;
21114   }
21115
21116   // Minor canonicalization of the accumulated shuffle mask to make it easier
21117   // to match below. All this does is detect masks with squential pairs of
21118   // elements, and shrink them to the half-width mask. It does this in a loop
21119   // so it will reduce the size of the mask to the minimal width mask which
21120   // performs an equivalent shuffle.
21121   SmallVector<int, 16> WidenedMask;
21122   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21123     Mask = std::move(WidenedMask);
21124     WidenedMask.clear();
21125   }
21126
21127   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21128                                 Subtarget);
21129 }
21130
21131 /// \brief Get the PSHUF-style mask from PSHUF node.
21132 ///
21133 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21134 /// PSHUF-style masks that can be reused with such instructions.
21135 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21136   MVT VT = N.getSimpleValueType();
21137   SmallVector<int, 4> Mask;
21138   bool IsUnary;
21139   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21140   (void)HaveMask;
21141   assert(HaveMask);
21142
21143   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21144   // matter. Check that the upper masks are repeats and remove them.
21145   if (VT.getSizeInBits() > 128) {
21146     int LaneElts = 128 / VT.getScalarSizeInBits();
21147 #ifndef NDEBUG
21148     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21149       for (int j = 0; j < LaneElts; ++j)
21150         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21151                "Mask doesn't repeat in high 128-bit lanes!");
21152 #endif
21153     Mask.resize(LaneElts);
21154   }
21155
21156   switch (N.getOpcode()) {
21157   case X86ISD::PSHUFD:
21158     return Mask;
21159   case X86ISD::PSHUFLW:
21160     Mask.resize(4);
21161     return Mask;
21162   case X86ISD::PSHUFHW:
21163     Mask.erase(Mask.begin(), Mask.begin() + 4);
21164     for (int &M : Mask)
21165       M -= 4;
21166     return Mask;
21167   default:
21168     llvm_unreachable("No valid shuffle instruction found!");
21169   }
21170 }
21171
21172 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21173 ///
21174 /// We walk up the chain and look for a combinable shuffle, skipping over
21175 /// shuffles that we could hoist this shuffle's transformation past without
21176 /// altering anything.
21177 static SDValue
21178 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21179                              SelectionDAG &DAG,
21180                              TargetLowering::DAGCombinerInfo &DCI) {
21181   assert(N.getOpcode() == X86ISD::PSHUFD &&
21182          "Called with something other than an x86 128-bit half shuffle!");
21183   SDLoc DL(N);
21184
21185   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21186   // of the shuffles in the chain so that we can form a fresh chain to replace
21187   // this one.
21188   SmallVector<SDValue, 8> Chain;
21189   SDValue V = N.getOperand(0);
21190   for (; V.hasOneUse(); V = V.getOperand(0)) {
21191     switch (V.getOpcode()) {
21192     default:
21193       return SDValue(); // Nothing combined!
21194
21195     case ISD::BITCAST:
21196       // Skip bitcasts as we always know the type for the target specific
21197       // instructions.
21198       continue;
21199
21200     case X86ISD::PSHUFD:
21201       // Found another dword shuffle.
21202       break;
21203
21204     case X86ISD::PSHUFLW:
21205       // Check that the low words (being shuffled) are the identity in the
21206       // dword shuffle, and the high words are self-contained.
21207       if (Mask[0] != 0 || Mask[1] != 1 ||
21208           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21209         return SDValue();
21210
21211       Chain.push_back(V);
21212       continue;
21213
21214     case X86ISD::PSHUFHW:
21215       // Check that the high words (being shuffled) are the identity in the
21216       // dword shuffle, and the low words are self-contained.
21217       if (Mask[2] != 2 || Mask[3] != 3 ||
21218           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21219         return SDValue();
21220
21221       Chain.push_back(V);
21222       continue;
21223
21224     case X86ISD::UNPCKL:
21225     case X86ISD::UNPCKH:
21226       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21227       // shuffle into a preceding word shuffle.
21228       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21229           V.getSimpleValueType().getScalarType() != MVT::i16)
21230         return SDValue();
21231
21232       // Search for a half-shuffle which we can combine with.
21233       unsigned CombineOp =
21234           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21235       if (V.getOperand(0) != V.getOperand(1) ||
21236           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21237         return SDValue();
21238       Chain.push_back(V);
21239       V = V.getOperand(0);
21240       do {
21241         switch (V.getOpcode()) {
21242         default:
21243           return SDValue(); // Nothing to combine.
21244
21245         case X86ISD::PSHUFLW:
21246         case X86ISD::PSHUFHW:
21247           if (V.getOpcode() == CombineOp)
21248             break;
21249
21250           Chain.push_back(V);
21251
21252           // Fallthrough!
21253         case ISD::BITCAST:
21254           V = V.getOperand(0);
21255           continue;
21256         }
21257         break;
21258       } while (V.hasOneUse());
21259       break;
21260     }
21261     // Break out of the loop if we break out of the switch.
21262     break;
21263   }
21264
21265   if (!V.hasOneUse())
21266     // We fell out of the loop without finding a viable combining instruction.
21267     return SDValue();
21268
21269   // Merge this node's mask and our incoming mask.
21270   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21271   for (int &M : Mask)
21272     M = VMask[M];
21273   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21274                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21275
21276   // Rebuild the chain around this new shuffle.
21277   while (!Chain.empty()) {
21278     SDValue W = Chain.pop_back_val();
21279
21280     if (V.getValueType() != W.getOperand(0).getValueType())
21281       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21282
21283     switch (W.getOpcode()) {
21284     default:
21285       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21286
21287     case X86ISD::UNPCKL:
21288     case X86ISD::UNPCKH:
21289       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21290       break;
21291
21292     case X86ISD::PSHUFD:
21293     case X86ISD::PSHUFLW:
21294     case X86ISD::PSHUFHW:
21295       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21296       break;
21297     }
21298   }
21299   if (V.getValueType() != N.getValueType())
21300     V = DAG.getBitcast(N.getValueType(), V);
21301
21302   // Return the new chain to replace N.
21303   return V;
21304 }
21305
21306 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21307 ///
21308 /// We walk up the chain, skipping shuffles of the other half and looking
21309 /// through shuffles which switch halves trying to find a shuffle of the same
21310 /// pair of dwords.
21311 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21312                                         SelectionDAG &DAG,
21313                                         TargetLowering::DAGCombinerInfo &DCI) {
21314   assert(
21315       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21316       "Called with something other than an x86 128-bit half shuffle!");
21317   SDLoc DL(N);
21318   unsigned CombineOpcode = N.getOpcode();
21319
21320   // Walk up a single-use chain looking for a combinable shuffle.
21321   SDValue V = N.getOperand(0);
21322   for (; V.hasOneUse(); V = V.getOperand(0)) {
21323     switch (V.getOpcode()) {
21324     default:
21325       return false; // Nothing combined!
21326
21327     case ISD::BITCAST:
21328       // Skip bitcasts as we always know the type for the target specific
21329       // instructions.
21330       continue;
21331
21332     case X86ISD::PSHUFLW:
21333     case X86ISD::PSHUFHW:
21334       if (V.getOpcode() == CombineOpcode)
21335         break;
21336
21337       // Other-half shuffles are no-ops.
21338       continue;
21339     }
21340     // Break out of the loop if we break out of the switch.
21341     break;
21342   }
21343
21344   if (!V.hasOneUse())
21345     // We fell out of the loop without finding a viable combining instruction.
21346     return false;
21347
21348   // Combine away the bottom node as its shuffle will be accumulated into
21349   // a preceding shuffle.
21350   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21351
21352   // Record the old value.
21353   SDValue Old = V;
21354
21355   // Merge this node's mask and our incoming mask (adjusted to account for all
21356   // the pshufd instructions encountered).
21357   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21358   for (int &M : Mask)
21359     M = VMask[M];
21360   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21361                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21362
21363   // Check that the shuffles didn't cancel each other out. If not, we need to
21364   // combine to the new one.
21365   if (Old != V)
21366     // Replace the combinable shuffle with the combined one, updating all users
21367     // so that we re-evaluate the chain here.
21368     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21369
21370   return true;
21371 }
21372
21373 /// \brief Try to combine x86 target specific shuffles.
21374 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21375                                            TargetLowering::DAGCombinerInfo &DCI,
21376                                            const X86Subtarget *Subtarget) {
21377   SDLoc DL(N);
21378   MVT VT = N.getSimpleValueType();
21379   SmallVector<int, 4> Mask;
21380
21381   switch (N.getOpcode()) {
21382   case X86ISD::PSHUFD:
21383   case X86ISD::PSHUFLW:
21384   case X86ISD::PSHUFHW:
21385     Mask = getPSHUFShuffleMask(N);
21386     assert(Mask.size() == 4);
21387     break;
21388   default:
21389     return SDValue();
21390   }
21391
21392   // Nuke no-op shuffles that show up after combining.
21393   if (isNoopShuffleMask(Mask))
21394     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21395
21396   // Look for simplifications involving one or two shuffle instructions.
21397   SDValue V = N.getOperand(0);
21398   switch (N.getOpcode()) {
21399   default:
21400     break;
21401   case X86ISD::PSHUFLW:
21402   case X86ISD::PSHUFHW:
21403     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21404
21405     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21406       return SDValue(); // We combined away this shuffle, so we're done.
21407
21408     // See if this reduces to a PSHUFD which is no more expensive and can
21409     // combine with more operations. Note that it has to at least flip the
21410     // dwords as otherwise it would have been removed as a no-op.
21411     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21412       int DMask[] = {0, 1, 2, 3};
21413       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21414       DMask[DOffset + 0] = DOffset + 1;
21415       DMask[DOffset + 1] = DOffset + 0;
21416       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21417       V = DAG.getBitcast(DVT, V);
21418       DCI.AddToWorklist(V.getNode());
21419       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21420                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21421       DCI.AddToWorklist(V.getNode());
21422       return DAG.getBitcast(VT, V);
21423     }
21424
21425     // Look for shuffle patterns which can be implemented as a single unpack.
21426     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21427     // only works when we have a PSHUFD followed by two half-shuffles.
21428     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21429         (V.getOpcode() == X86ISD::PSHUFLW ||
21430          V.getOpcode() == X86ISD::PSHUFHW) &&
21431         V.getOpcode() != N.getOpcode() &&
21432         V.hasOneUse()) {
21433       SDValue D = V.getOperand(0);
21434       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21435         D = D.getOperand(0);
21436       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21437         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21438         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21439         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21440         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21441         int WordMask[8];
21442         for (int i = 0; i < 4; ++i) {
21443           WordMask[i + NOffset] = Mask[i] + NOffset;
21444           WordMask[i + VOffset] = VMask[i] + VOffset;
21445         }
21446         // Map the word mask through the DWord mask.
21447         int MappedMask[8];
21448         for (int i = 0; i < 8; ++i)
21449           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21450         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21451             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21452           // We can replace all three shuffles with an unpack.
21453           V = DAG.getBitcast(VT, D.getOperand(0));
21454           DCI.AddToWorklist(V.getNode());
21455           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21456                                                 : X86ISD::UNPCKH,
21457                              DL, VT, V, V);
21458         }
21459       }
21460     }
21461
21462     break;
21463
21464   case X86ISD::PSHUFD:
21465     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21466       return NewN;
21467
21468     break;
21469   }
21470
21471   return SDValue();
21472 }
21473
21474 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21475 ///
21476 /// We combine this directly on the abstract vector shuffle nodes so it is
21477 /// easier to generically match. We also insert dummy vector shuffle nodes for
21478 /// the operands which explicitly discard the lanes which are unused by this
21479 /// operation to try to flow through the rest of the combiner the fact that
21480 /// they're unused.
21481 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21482   SDLoc DL(N);
21483   EVT VT = N->getValueType(0);
21484
21485   // We only handle target-independent shuffles.
21486   // FIXME: It would be easy and harmless to use the target shuffle mask
21487   // extraction tool to support more.
21488   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21489     return SDValue();
21490
21491   auto *SVN = cast<ShuffleVectorSDNode>(N);
21492   ArrayRef<int> Mask = SVN->getMask();
21493   SDValue V1 = N->getOperand(0);
21494   SDValue V2 = N->getOperand(1);
21495
21496   // We require the first shuffle operand to be the SUB node, and the second to
21497   // be the ADD node.
21498   // FIXME: We should support the commuted patterns.
21499   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21500     return SDValue();
21501
21502   // If there are other uses of these operations we can't fold them.
21503   if (!V1->hasOneUse() || !V2->hasOneUse())
21504     return SDValue();
21505
21506   // Ensure that both operations have the same operands. Note that we can
21507   // commute the FADD operands.
21508   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21509   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21510       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21511     return SDValue();
21512
21513   // We're looking for blends between FADD and FSUB nodes. We insist on these
21514   // nodes being lined up in a specific expected pattern.
21515   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21516         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21517         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21518     return SDValue();
21519
21520   // Only specific types are legal at this point, assert so we notice if and
21521   // when these change.
21522   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21523           VT == MVT::v4f64) &&
21524          "Unknown vector type encountered!");
21525
21526   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21527 }
21528
21529 /// PerformShuffleCombine - Performs several different shuffle combines.
21530 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21531                                      TargetLowering::DAGCombinerInfo &DCI,
21532                                      const X86Subtarget *Subtarget) {
21533   SDLoc dl(N);
21534   SDValue N0 = N->getOperand(0);
21535   SDValue N1 = N->getOperand(1);
21536   EVT VT = N->getValueType(0);
21537
21538   // Don't create instructions with illegal types after legalize types has run.
21539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21540   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21541     return SDValue();
21542
21543   // If we have legalized the vector types, look for blends of FADD and FSUB
21544   // nodes that we can fuse into an ADDSUB node.
21545   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21546     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21547       return AddSub;
21548
21549   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21550   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21551       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21552     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21553
21554   // During Type Legalization, when promoting illegal vector types,
21555   // the backend might introduce new shuffle dag nodes and bitcasts.
21556   //
21557   // This code performs the following transformation:
21558   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21559   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21560   //
21561   // We do this only if both the bitcast and the BINOP dag nodes have
21562   // one use. Also, perform this transformation only if the new binary
21563   // operation is legal. This is to avoid introducing dag nodes that
21564   // potentially need to be further expanded (or custom lowered) into a
21565   // less optimal sequence of dag nodes.
21566   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21567       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21568       N0.getOpcode() == ISD::BITCAST) {
21569     SDValue BC0 = N0.getOperand(0);
21570     EVT SVT = BC0.getValueType();
21571     unsigned Opcode = BC0.getOpcode();
21572     unsigned NumElts = VT.getVectorNumElements();
21573
21574     if (BC0.hasOneUse() && SVT.isVector() &&
21575         SVT.getVectorNumElements() * 2 == NumElts &&
21576         TLI.isOperationLegal(Opcode, VT)) {
21577       bool CanFold = false;
21578       switch (Opcode) {
21579       default : break;
21580       case ISD::ADD :
21581       case ISD::FADD :
21582       case ISD::SUB :
21583       case ISD::FSUB :
21584       case ISD::MUL :
21585       case ISD::FMUL :
21586         CanFold = true;
21587       }
21588
21589       unsigned SVTNumElts = SVT.getVectorNumElements();
21590       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21591       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21592         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21593       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21594         CanFold = SVOp->getMaskElt(i) < 0;
21595
21596       if (CanFold) {
21597         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21598         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21599         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21600         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21601       }
21602     }
21603   }
21604
21605   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21606   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21607   // consecutive, non-overlapping, and in the right order.
21608   SmallVector<SDValue, 16> Elts;
21609   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21610     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21611
21612   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21613     return LD;
21614
21615   if (isTargetShuffle(N->getOpcode())) {
21616     SDValue Shuffle =
21617         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21618     if (Shuffle.getNode())
21619       return Shuffle;
21620
21621     // Try recursively combining arbitrary sequences of x86 shuffle
21622     // instructions into higher-order shuffles. We do this after combining
21623     // specific PSHUF instruction sequences into their minimal form so that we
21624     // can evaluate how many specialized shuffle instructions are involved in
21625     // a particular chain.
21626     SmallVector<int, 1> NonceMask; // Just a placeholder.
21627     NonceMask.push_back(0);
21628     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21629                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21630                                       DCI, Subtarget))
21631       return SDValue(); // This routine will use CombineTo to replace N.
21632   }
21633
21634   return SDValue();
21635 }
21636
21637 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21638 /// specific shuffle of a load can be folded into a single element load.
21639 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21640 /// shuffles have been custom lowered so we need to handle those here.
21641 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21642                                          TargetLowering::DAGCombinerInfo &DCI) {
21643   if (DCI.isBeforeLegalizeOps())
21644     return SDValue();
21645
21646   SDValue InVec = N->getOperand(0);
21647   SDValue EltNo = N->getOperand(1);
21648
21649   if (!isa<ConstantSDNode>(EltNo))
21650     return SDValue();
21651
21652   EVT OriginalVT = InVec.getValueType();
21653
21654   if (InVec.getOpcode() == ISD::BITCAST) {
21655     // Don't duplicate a load with other uses.
21656     if (!InVec.hasOneUse())
21657       return SDValue();
21658     EVT BCVT = InVec.getOperand(0).getValueType();
21659     if (!BCVT.isVector() ||
21660         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21661       return SDValue();
21662     InVec = InVec.getOperand(0);
21663   }
21664
21665   EVT CurrentVT = InVec.getValueType();
21666
21667   if (!isTargetShuffle(InVec.getOpcode()))
21668     return SDValue();
21669
21670   // Don't duplicate a load with other uses.
21671   if (!InVec.hasOneUse())
21672     return SDValue();
21673
21674   SmallVector<int, 16> ShuffleMask;
21675   bool UnaryShuffle;
21676   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21677                             ShuffleMask, UnaryShuffle))
21678     return SDValue();
21679
21680   // Select the input vector, guarding against out of range extract vector.
21681   unsigned NumElems = CurrentVT.getVectorNumElements();
21682   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21683   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21684   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21685                                          : InVec.getOperand(1);
21686
21687   // If inputs to shuffle are the same for both ops, then allow 2 uses
21688   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21689                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21690
21691   if (LdNode.getOpcode() == ISD::BITCAST) {
21692     // Don't duplicate a load with other uses.
21693     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21694       return SDValue();
21695
21696     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21697     LdNode = LdNode.getOperand(0);
21698   }
21699
21700   if (!ISD::isNormalLoad(LdNode.getNode()))
21701     return SDValue();
21702
21703   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21704
21705   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21706     return SDValue();
21707
21708   EVT EltVT = N->getValueType(0);
21709   // If there's a bitcast before the shuffle, check if the load type and
21710   // alignment is valid.
21711   unsigned Align = LN0->getAlignment();
21712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21713   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
21714       EltVT.getTypeForEVT(*DAG.getContext()));
21715
21716   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21717     return SDValue();
21718
21719   // All checks match so transform back to vector_shuffle so that DAG combiner
21720   // can finish the job
21721   SDLoc dl(N);
21722
21723   // Create shuffle node taking into account the case that its a unary shuffle
21724   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21725                                    : InVec.getOperand(1);
21726   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21727                                  InVec.getOperand(0), Shuffle,
21728                                  &ShuffleMask[0]);
21729   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21730   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21731                      EltNo);
21732 }
21733
21734 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21735 /// special and don't usually play with other vector types, it's better to
21736 /// handle them early to be sure we emit efficient code by avoiding
21737 /// store-load conversions.
21738 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21739   if (N->getValueType(0) != MVT::x86mmx ||
21740       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21741       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21742     return SDValue();
21743
21744   SDValue V = N->getOperand(0);
21745   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21746   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21747     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21748                        N->getValueType(0), V.getOperand(0));
21749
21750   return SDValue();
21751 }
21752
21753 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21754 /// generation and convert it from being a bunch of shuffles and extracts
21755 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21756 /// storing the value and loading scalars back, while for x64 we should
21757 /// use 64-bit extracts and shifts.
21758 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21759                                          TargetLowering::DAGCombinerInfo &DCI) {
21760   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21761     return NewOp;
21762
21763   SDValue InputVector = N->getOperand(0);
21764   SDLoc dl(InputVector);
21765   // Detect mmx to i32 conversion through a v2i32 elt extract.
21766   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21767       N->getValueType(0) == MVT::i32 &&
21768       InputVector.getValueType() == MVT::v2i32) {
21769
21770     // The bitcast source is a direct mmx result.
21771     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21772     if (MMXSrc.getValueType() == MVT::x86mmx)
21773       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21774                          N->getValueType(0),
21775                          InputVector.getNode()->getOperand(0));
21776
21777     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21778     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21779     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21780         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21781         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21782         MMXSrcOp.getValueType() == MVT::v1i64 &&
21783         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21784       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21785                          N->getValueType(0),
21786                          MMXSrcOp.getOperand(0));
21787   }
21788
21789   EVT VT = N->getValueType(0);
21790
21791   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21792       InputVector.getOpcode() == ISD::BITCAST &&
21793       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21794     uint64_t ExtractedElt =
21795           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21796     uint64_t InputValue =
21797           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21798     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21799     return DAG.getConstant(Res, dl, MVT::i1);
21800   }
21801   // Only operate on vectors of 4 elements, where the alternative shuffling
21802   // gets to be more expensive.
21803   if (InputVector.getValueType() != MVT::v4i32)
21804     return SDValue();
21805
21806   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21807   // single use which is a sign-extend or zero-extend, and all elements are
21808   // used.
21809   SmallVector<SDNode *, 4> Uses;
21810   unsigned ExtractedElements = 0;
21811   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21812        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21813     if (UI.getUse().getResNo() != InputVector.getResNo())
21814       return SDValue();
21815
21816     SDNode *Extract = *UI;
21817     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21818       return SDValue();
21819
21820     if (Extract->getValueType(0) != MVT::i32)
21821       return SDValue();
21822     if (!Extract->hasOneUse())
21823       return SDValue();
21824     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21825         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21826       return SDValue();
21827     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21828       return SDValue();
21829
21830     // Record which element was extracted.
21831     ExtractedElements |=
21832       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21833
21834     Uses.push_back(Extract);
21835   }
21836
21837   // If not all the elements were used, this may not be worthwhile.
21838   if (ExtractedElements != 15)
21839     return SDValue();
21840
21841   // Ok, we've now decided to do the transformation.
21842   // If 64-bit shifts are legal, use the extract-shift sequence,
21843   // otherwise bounce the vector off the cache.
21844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21845   SDValue Vals[4];
21846
21847   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21848     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21849     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21850     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21851       DAG.getConstant(0, dl, VecIdxTy));
21852     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21853       DAG.getConstant(1, dl, VecIdxTy));
21854
21855     SDValue ShAmt = DAG.getConstant(32, dl,
21856       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21857     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21858     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21859       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21860     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21861     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21862       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21863   } else {
21864     // Store the value to a temporary stack slot.
21865     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21866     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21867       MachinePointerInfo(), false, false, 0);
21868
21869     EVT ElementType = InputVector.getValueType().getVectorElementType();
21870     unsigned EltSize = ElementType.getSizeInBits() / 8;
21871
21872     // Replace each use (extract) with a load of the appropriate element.
21873     for (unsigned i = 0; i < 4; ++i) {
21874       uint64_t Offset = EltSize * i;
21875       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21876
21877       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21878                                        StackPtr, OffsetVal);
21879
21880       // Load the scalar.
21881       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21882                             ScalarAddr, MachinePointerInfo(),
21883                             false, false, false, 0);
21884
21885     }
21886   }
21887
21888   // Replace the extracts
21889   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21890     UE = Uses.end(); UI != UE; ++UI) {
21891     SDNode *Extract = *UI;
21892
21893     SDValue Idx = Extract->getOperand(1);
21894     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21895     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21896   }
21897
21898   // The replacement was made in place; don't return anything.
21899   return SDValue();
21900 }
21901
21902 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21903 static std::pair<unsigned, bool>
21904 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21905                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21906   if (!VT.isVector())
21907     return std::make_pair(0, false);
21908
21909   bool NeedSplit = false;
21910   switch (VT.getSimpleVT().SimpleTy) {
21911   default: return std::make_pair(0, false);
21912   case MVT::v4i64:
21913   case MVT::v2i64:
21914     if (!Subtarget->hasVLX())
21915       return std::make_pair(0, false);
21916     break;
21917   case MVT::v64i8:
21918   case MVT::v32i16:
21919     if (!Subtarget->hasBWI())
21920       return std::make_pair(0, false);
21921     break;
21922   case MVT::v16i32:
21923   case MVT::v8i64:
21924     if (!Subtarget->hasAVX512())
21925       return std::make_pair(0, false);
21926     break;
21927   case MVT::v32i8:
21928   case MVT::v16i16:
21929   case MVT::v8i32:
21930     if (!Subtarget->hasAVX2())
21931       NeedSplit = true;
21932     if (!Subtarget->hasAVX())
21933       return std::make_pair(0, false);
21934     break;
21935   case MVT::v16i8:
21936   case MVT::v8i16:
21937   case MVT::v4i32:
21938     if (!Subtarget->hasSSE2())
21939       return std::make_pair(0, false);
21940   }
21941
21942   // SSE2 has only a small subset of the operations.
21943   bool hasUnsigned = Subtarget->hasSSE41() ||
21944                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21945   bool hasSigned = Subtarget->hasSSE41() ||
21946                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21947
21948   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21949
21950   unsigned Opc = 0;
21951   // Check for x CC y ? x : y.
21952   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21953       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21954     switch (CC) {
21955     default: break;
21956     case ISD::SETULT:
21957     case ISD::SETULE:
21958       Opc = hasUnsigned ? ISD::UMIN : 0; break;
21959     case ISD::SETUGT:
21960     case ISD::SETUGE:
21961       Opc = hasUnsigned ? ISD::UMAX : 0; break;
21962     case ISD::SETLT:
21963     case ISD::SETLE:
21964       Opc = hasSigned ? ISD::SMIN : 0; break;
21965     case ISD::SETGT:
21966     case ISD::SETGE:
21967       Opc = hasSigned ? ISD::SMAX : 0; break;
21968     }
21969   // Check for x CC y ? y : x -- a min/max with reversed arms.
21970   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21971              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21972     switch (CC) {
21973     default: break;
21974     case ISD::SETULT:
21975     case ISD::SETULE:
21976       Opc = hasUnsigned ? ISD::UMAX : 0; break;
21977     case ISD::SETUGT:
21978     case ISD::SETUGE:
21979       Opc = hasUnsigned ? ISD::UMIN : 0; break;
21980     case ISD::SETLT:
21981     case ISD::SETLE:
21982       Opc = hasSigned ? ISD::SMAX : 0; break;
21983     case ISD::SETGT:
21984     case ISD::SETGE:
21985       Opc = hasSigned ? ISD::SMIN : 0; break;
21986     }
21987   }
21988
21989   return std::make_pair(Opc, NeedSplit);
21990 }
21991
21992 static SDValue
21993 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21994                                       const X86Subtarget *Subtarget) {
21995   SDLoc dl(N);
21996   SDValue Cond = N->getOperand(0);
21997   SDValue LHS = N->getOperand(1);
21998   SDValue RHS = N->getOperand(2);
21999
22000   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22001     SDValue CondSrc = Cond->getOperand(0);
22002     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22003       Cond = CondSrc->getOperand(0);
22004   }
22005
22006   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22007     return SDValue();
22008
22009   // A vselect where all conditions and data are constants can be optimized into
22010   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22011   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22012       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22013     return SDValue();
22014
22015   unsigned MaskValue = 0;
22016   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22017     return SDValue();
22018
22019   MVT VT = N->getSimpleValueType(0);
22020   unsigned NumElems = VT.getVectorNumElements();
22021   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22022   for (unsigned i = 0; i < NumElems; ++i) {
22023     // Be sure we emit undef where we can.
22024     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22025       ShuffleMask[i] = -1;
22026     else
22027       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22028   }
22029
22030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22031   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22032     return SDValue();
22033   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22034 }
22035
22036 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22037 /// nodes.
22038 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22039                                     TargetLowering::DAGCombinerInfo &DCI,
22040                                     const X86Subtarget *Subtarget) {
22041   SDLoc DL(N);
22042   SDValue Cond = N->getOperand(0);
22043   // Get the LHS/RHS of the select.
22044   SDValue LHS = N->getOperand(1);
22045   SDValue RHS = N->getOperand(2);
22046   EVT VT = LHS.getValueType();
22047   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22048
22049   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22050   // instructions match the semantics of the common C idiom x<y?x:y but not
22051   // x<=y?x:y, because of how they handle negative zero (which can be
22052   // ignored in unsafe-math mode).
22053   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22054   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22055       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22056       (Subtarget->hasSSE2() ||
22057        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22058     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22059
22060     unsigned Opcode = 0;
22061     // Check for x CC y ? x : y.
22062     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22063         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22064       switch (CC) {
22065       default: break;
22066       case ISD::SETULT:
22067         // Converting this to a min would handle NaNs incorrectly, and swapping
22068         // the operands would cause it to handle comparisons between positive
22069         // and negative zero incorrectly.
22070         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22071           if (!DAG.getTarget().Options.UnsafeFPMath &&
22072               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22073             break;
22074           std::swap(LHS, RHS);
22075         }
22076         Opcode = X86ISD::FMIN;
22077         break;
22078       case ISD::SETOLE:
22079         // Converting this to a min would handle comparisons between positive
22080         // and negative zero incorrectly.
22081         if (!DAG.getTarget().Options.UnsafeFPMath &&
22082             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22083           break;
22084         Opcode = X86ISD::FMIN;
22085         break;
22086       case ISD::SETULE:
22087         // Converting this to a min would handle both negative zeros and NaNs
22088         // incorrectly, but we can swap the operands to fix both.
22089         std::swap(LHS, RHS);
22090       case ISD::SETOLT:
22091       case ISD::SETLT:
22092       case ISD::SETLE:
22093         Opcode = X86ISD::FMIN;
22094         break;
22095
22096       case ISD::SETOGE:
22097         // Converting this to a max would handle comparisons between positive
22098         // and negative zero incorrectly.
22099         if (!DAG.getTarget().Options.UnsafeFPMath &&
22100             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22101           break;
22102         Opcode = X86ISD::FMAX;
22103         break;
22104       case ISD::SETUGT:
22105         // Converting this to a max would handle NaNs incorrectly, and swapping
22106         // the operands would cause it to handle comparisons between positive
22107         // and negative zero incorrectly.
22108         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22109           if (!DAG.getTarget().Options.UnsafeFPMath &&
22110               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22111             break;
22112           std::swap(LHS, RHS);
22113         }
22114         Opcode = X86ISD::FMAX;
22115         break;
22116       case ISD::SETUGE:
22117         // Converting this to a max would handle both negative zeros and NaNs
22118         // incorrectly, but we can swap the operands to fix both.
22119         std::swap(LHS, RHS);
22120       case ISD::SETOGT:
22121       case ISD::SETGT:
22122       case ISD::SETGE:
22123         Opcode = X86ISD::FMAX;
22124         break;
22125       }
22126     // Check for x CC y ? y : x -- a min/max with reversed arms.
22127     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22128                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22129       switch (CC) {
22130       default: break;
22131       case ISD::SETOGE:
22132         // Converting this to a min would handle comparisons between positive
22133         // and negative zero incorrectly, and swapping the operands would
22134         // cause it to handle NaNs incorrectly.
22135         if (!DAG.getTarget().Options.UnsafeFPMath &&
22136             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22137           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22138             break;
22139           std::swap(LHS, RHS);
22140         }
22141         Opcode = X86ISD::FMIN;
22142         break;
22143       case ISD::SETUGT:
22144         // Converting this to a min would handle NaNs incorrectly.
22145         if (!DAG.getTarget().Options.UnsafeFPMath &&
22146             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22147           break;
22148         Opcode = X86ISD::FMIN;
22149         break;
22150       case ISD::SETUGE:
22151         // Converting this to a min would handle both negative zeros and NaNs
22152         // incorrectly, but we can swap the operands to fix both.
22153         std::swap(LHS, RHS);
22154       case ISD::SETOGT:
22155       case ISD::SETGT:
22156       case ISD::SETGE:
22157         Opcode = X86ISD::FMIN;
22158         break;
22159
22160       case ISD::SETULT:
22161         // Converting this to a max would handle NaNs incorrectly.
22162         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22163           break;
22164         Opcode = X86ISD::FMAX;
22165         break;
22166       case ISD::SETOLE:
22167         // Converting this to a max would handle comparisons between positive
22168         // and negative zero incorrectly, and swapping the operands would
22169         // cause it to handle NaNs incorrectly.
22170         if (!DAG.getTarget().Options.UnsafeFPMath &&
22171             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22172           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22173             break;
22174           std::swap(LHS, RHS);
22175         }
22176         Opcode = X86ISD::FMAX;
22177         break;
22178       case ISD::SETULE:
22179         // Converting this to a max would handle both negative zeros and NaNs
22180         // incorrectly, but we can swap the operands to fix both.
22181         std::swap(LHS, RHS);
22182       case ISD::SETOLT:
22183       case ISD::SETLT:
22184       case ISD::SETLE:
22185         Opcode = X86ISD::FMAX;
22186         break;
22187       }
22188     }
22189
22190     if (Opcode)
22191       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22192   }
22193
22194   EVT CondVT = Cond.getValueType();
22195   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22196       CondVT.getVectorElementType() == MVT::i1) {
22197     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22198     // lowering on KNL. In this case we convert it to
22199     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22200     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22201     // Since SKX these selects have a proper lowering.
22202     EVT OpVT = LHS.getValueType();
22203     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22204         (OpVT.getVectorElementType() == MVT::i8 ||
22205          OpVT.getVectorElementType() == MVT::i16) &&
22206         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22207       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22208       DCI.AddToWorklist(Cond.getNode());
22209       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22210     }
22211   }
22212   // If this is a select between two integer constants, try to do some
22213   // optimizations.
22214   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22215     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22216       // Don't do this for crazy integer types.
22217       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22218         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22219         // so that TrueC (the true value) is larger than FalseC.
22220         bool NeedsCondInvert = false;
22221
22222         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22223             // Efficiently invertible.
22224             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22225              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22226               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22227           NeedsCondInvert = true;
22228           std::swap(TrueC, FalseC);
22229         }
22230
22231         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22232         if (FalseC->getAPIntValue() == 0 &&
22233             TrueC->getAPIntValue().isPowerOf2()) {
22234           if (NeedsCondInvert) // Invert the condition if needed.
22235             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22236                                DAG.getConstant(1, DL, Cond.getValueType()));
22237
22238           // Zero extend the condition if needed.
22239           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22240
22241           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22242           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22243                              DAG.getConstant(ShAmt, DL, MVT::i8));
22244         }
22245
22246         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22247         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22248           if (NeedsCondInvert) // Invert the condition if needed.
22249             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22250                                DAG.getConstant(1, DL, Cond.getValueType()));
22251
22252           // Zero extend the condition if needed.
22253           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22254                              FalseC->getValueType(0), Cond);
22255           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22256                              SDValue(FalseC, 0));
22257         }
22258
22259         // Optimize cases that will turn into an LEA instruction.  This requires
22260         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22261         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22262           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22263           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22264
22265           bool isFastMultiplier = false;
22266           if (Diff < 10) {
22267             switch ((unsigned char)Diff) {
22268               default: break;
22269               case 1:  // result = add base, cond
22270               case 2:  // result = lea base(    , cond*2)
22271               case 3:  // result = lea base(cond, cond*2)
22272               case 4:  // result = lea base(    , cond*4)
22273               case 5:  // result = lea base(cond, cond*4)
22274               case 8:  // result = lea base(    , cond*8)
22275               case 9:  // result = lea base(cond, cond*8)
22276                 isFastMultiplier = true;
22277                 break;
22278             }
22279           }
22280
22281           if (isFastMultiplier) {
22282             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22283             if (NeedsCondInvert) // Invert the condition if needed.
22284               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22285                                  DAG.getConstant(1, DL, Cond.getValueType()));
22286
22287             // Zero extend the condition if needed.
22288             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22289                                Cond);
22290             // Scale the condition by the difference.
22291             if (Diff != 1)
22292               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22293                                  DAG.getConstant(Diff, DL,
22294                                                  Cond.getValueType()));
22295
22296             // Add the base if non-zero.
22297             if (FalseC->getAPIntValue() != 0)
22298               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22299                                  SDValue(FalseC, 0));
22300             return Cond;
22301           }
22302         }
22303       }
22304   }
22305
22306   // Canonicalize max and min:
22307   // (x > y) ? x : y -> (x >= y) ? x : y
22308   // (x < y) ? x : y -> (x <= y) ? x : y
22309   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22310   // the need for an extra compare
22311   // against zero. e.g.
22312   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22313   // subl   %esi, %edi
22314   // testl  %edi, %edi
22315   // movl   $0, %eax
22316   // cmovgl %edi, %eax
22317   // =>
22318   // xorl   %eax, %eax
22319   // subl   %esi, $edi
22320   // cmovsl %eax, %edi
22321   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22322       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22323       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22324     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22325     switch (CC) {
22326     default: break;
22327     case ISD::SETLT:
22328     case ISD::SETGT: {
22329       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22330       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22331                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22332       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22333     }
22334     }
22335   }
22336
22337   // Early exit check
22338   if (!TLI.isTypeLegal(VT))
22339     return SDValue();
22340
22341   // Match VSELECTs into subs with unsigned saturation.
22342   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22343       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22344       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22345        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22346     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22347
22348     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22349     // left side invert the predicate to simplify logic below.
22350     SDValue Other;
22351     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22352       Other = RHS;
22353       CC = ISD::getSetCCInverse(CC, true);
22354     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22355       Other = LHS;
22356     }
22357
22358     if (Other.getNode() && Other->getNumOperands() == 2 &&
22359         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22360       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22361       SDValue CondRHS = Cond->getOperand(1);
22362
22363       // Look for a general sub with unsigned saturation first.
22364       // x >= y ? x-y : 0 --> subus x, y
22365       // x >  y ? x-y : 0 --> subus x, y
22366       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22367           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22368         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22369
22370       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22371         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22372           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22373             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22374               // If the RHS is a constant we have to reverse the const
22375               // canonicalization.
22376               // x > C-1 ? x+-C : 0 --> subus x, C
22377               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22378                   CondRHSConst->getAPIntValue() ==
22379                       (-OpRHSConst->getAPIntValue() - 1))
22380                 return DAG.getNode(
22381                     X86ISD::SUBUS, DL, VT, OpLHS,
22382                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22383
22384           // Another special case: If C was a sign bit, the sub has been
22385           // canonicalized into a xor.
22386           // FIXME: Would it be better to use computeKnownBits to determine
22387           //        whether it's safe to decanonicalize the xor?
22388           // x s< 0 ? x^C : 0 --> subus x, C
22389           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22390               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22391               OpRHSConst->getAPIntValue().isSignBit())
22392             // Note that we have to rebuild the RHS constant here to ensure we
22393             // don't rely on particular values of undef lanes.
22394             return DAG.getNode(
22395                 X86ISD::SUBUS, DL, VT, OpLHS,
22396                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22397         }
22398     }
22399   }
22400
22401   // Try to match a min/max vector operation.
22402   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22403     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22404     unsigned Opc = ret.first;
22405     bool NeedSplit = ret.second;
22406
22407     if (Opc && NeedSplit) {
22408       unsigned NumElems = VT.getVectorNumElements();
22409       // Extract the LHS vectors
22410       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22411       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22412
22413       // Extract the RHS vectors
22414       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22415       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22416
22417       // Create min/max for each subvector
22418       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22419       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22420
22421       // Merge the result
22422       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22423     } else if (Opc)
22424       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22425   }
22426
22427   // Simplify vector selection if condition value type matches vselect
22428   // operand type
22429   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22430     assert(Cond.getValueType().isVector() &&
22431            "vector select expects a vector selector!");
22432
22433     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22434     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22435
22436     // Try invert the condition if true value is not all 1s and false value
22437     // is not all 0s.
22438     if (!TValIsAllOnes && !FValIsAllZeros &&
22439         // Check if the selector will be produced by CMPP*/PCMP*
22440         Cond.getOpcode() == ISD::SETCC &&
22441         // Check if SETCC has already been promoted
22442         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
22443       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22444       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22445
22446       if (TValIsAllZeros || FValIsAllOnes) {
22447         SDValue CC = Cond.getOperand(2);
22448         ISD::CondCode NewCC =
22449           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22450                                Cond.getOperand(0).getValueType().isInteger());
22451         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22452         std::swap(LHS, RHS);
22453         TValIsAllOnes = FValIsAllOnes;
22454         FValIsAllZeros = TValIsAllZeros;
22455       }
22456     }
22457
22458     if (TValIsAllOnes || FValIsAllZeros) {
22459       SDValue Ret;
22460
22461       if (TValIsAllOnes && FValIsAllZeros)
22462         Ret = Cond;
22463       else if (TValIsAllOnes)
22464         Ret =
22465             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22466       else if (FValIsAllZeros)
22467         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22468                           DAG.getBitcast(CondVT, LHS));
22469
22470       return DAG.getBitcast(VT, Ret);
22471     }
22472   }
22473
22474   // We should generate an X86ISD::BLENDI from a vselect if its argument
22475   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22476   // constants. This specific pattern gets generated when we split a
22477   // selector for a 512 bit vector in a machine without AVX512 (but with
22478   // 256-bit vectors), during legalization:
22479   //
22480   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22481   //
22482   // Iff we find this pattern and the build_vectors are built from
22483   // constants, we translate the vselect into a shuffle_vector that we
22484   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22485   if ((N->getOpcode() == ISD::VSELECT ||
22486        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22487       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22488     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22489     if (Shuffle.getNode())
22490       return Shuffle;
22491   }
22492
22493   // If this is a *dynamic* select (non-constant condition) and we can match
22494   // this node with one of the variable blend instructions, restructure the
22495   // condition so that the blends can use the high bit of each element and use
22496   // SimplifyDemandedBits to simplify the condition operand.
22497   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22498       !DCI.isBeforeLegalize() &&
22499       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22500     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22501
22502     // Don't optimize vector selects that map to mask-registers.
22503     if (BitWidth == 1)
22504       return SDValue();
22505
22506     // We can only handle the cases where VSELECT is directly legal on the
22507     // subtarget. We custom lower VSELECT nodes with constant conditions and
22508     // this makes it hard to see whether a dynamic VSELECT will correctly
22509     // lower, so we both check the operation's status and explicitly handle the
22510     // cases where a *dynamic* blend will fail even though a constant-condition
22511     // blend could be custom lowered.
22512     // FIXME: We should find a better way to handle this class of problems.
22513     // Potentially, we should combine constant-condition vselect nodes
22514     // pre-legalization into shuffles and not mark as many types as custom
22515     // lowered.
22516     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22517       return SDValue();
22518     // FIXME: We don't support i16-element blends currently. We could and
22519     // should support them by making *all* the bits in the condition be set
22520     // rather than just the high bit and using an i8-element blend.
22521     if (VT.getScalarType() == MVT::i16)
22522       return SDValue();
22523     // Dynamic blending was only available from SSE4.1 onward.
22524     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22525       return SDValue();
22526     // Byte blends are only available in AVX2
22527     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22528         !Subtarget->hasAVX2())
22529       return SDValue();
22530
22531     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22532     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22533
22534     APInt KnownZero, KnownOne;
22535     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22536                                           DCI.isBeforeLegalizeOps());
22537     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22538         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22539                                  TLO)) {
22540       // If we changed the computation somewhere in the DAG, this change
22541       // will affect all users of Cond.
22542       // Make sure it is fine and update all the nodes so that we do not
22543       // use the generic VSELECT anymore. Otherwise, we may perform
22544       // wrong optimizations as we messed up with the actual expectation
22545       // for the vector boolean values.
22546       if (Cond != TLO.Old) {
22547         // Check all uses of that condition operand to check whether it will be
22548         // consumed by non-BLEND instructions, which may depend on all bits are
22549         // set properly.
22550         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22551              I != E; ++I)
22552           if (I->getOpcode() != ISD::VSELECT)
22553             // TODO: Add other opcodes eventually lowered into BLEND.
22554             return SDValue();
22555
22556         // Update all the users of the condition, before committing the change,
22557         // so that the VSELECT optimizations that expect the correct vector
22558         // boolean value will not be triggered.
22559         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22560              I != E; ++I)
22561           DAG.ReplaceAllUsesOfValueWith(
22562               SDValue(*I, 0),
22563               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22564                           Cond, I->getOperand(1), I->getOperand(2)));
22565         DCI.CommitTargetLoweringOpt(TLO);
22566         return SDValue();
22567       }
22568       // At this point, only Cond is changed. Change the condition
22569       // just for N to keep the opportunity to optimize all other
22570       // users their own way.
22571       DAG.ReplaceAllUsesOfValueWith(
22572           SDValue(N, 0),
22573           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22574                       TLO.New, N->getOperand(1), N->getOperand(2)));
22575       return SDValue();
22576     }
22577   }
22578
22579   return SDValue();
22580 }
22581
22582 // Check whether a boolean test is testing a boolean value generated by
22583 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22584 // code.
22585 //
22586 // Simplify the following patterns:
22587 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22588 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22589 // to (Op EFLAGS Cond)
22590 //
22591 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22592 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22593 // to (Op EFLAGS !Cond)
22594 //
22595 // where Op could be BRCOND or CMOV.
22596 //
22597 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22598   // Quit if not CMP and SUB with its value result used.
22599   if (Cmp.getOpcode() != X86ISD::CMP &&
22600       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22601       return SDValue();
22602
22603   // Quit if not used as a boolean value.
22604   if (CC != X86::COND_E && CC != X86::COND_NE)
22605     return SDValue();
22606
22607   // Check CMP operands. One of them should be 0 or 1 and the other should be
22608   // an SetCC or extended from it.
22609   SDValue Op1 = Cmp.getOperand(0);
22610   SDValue Op2 = Cmp.getOperand(1);
22611
22612   SDValue SetCC;
22613   const ConstantSDNode* C = nullptr;
22614   bool needOppositeCond = (CC == X86::COND_E);
22615   bool checkAgainstTrue = false; // Is it a comparison against 1?
22616
22617   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22618     SetCC = Op2;
22619   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22620     SetCC = Op1;
22621   else // Quit if all operands are not constants.
22622     return SDValue();
22623
22624   if (C->getZExtValue() == 1) {
22625     needOppositeCond = !needOppositeCond;
22626     checkAgainstTrue = true;
22627   } else if (C->getZExtValue() != 0)
22628     // Quit if the constant is neither 0 or 1.
22629     return SDValue();
22630
22631   bool truncatedToBoolWithAnd = false;
22632   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22633   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22634          SetCC.getOpcode() == ISD::TRUNCATE ||
22635          SetCC.getOpcode() == ISD::AND) {
22636     if (SetCC.getOpcode() == ISD::AND) {
22637       int OpIdx = -1;
22638       ConstantSDNode *CS;
22639       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22640           CS->getZExtValue() == 1)
22641         OpIdx = 1;
22642       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22643           CS->getZExtValue() == 1)
22644         OpIdx = 0;
22645       if (OpIdx == -1)
22646         break;
22647       SetCC = SetCC.getOperand(OpIdx);
22648       truncatedToBoolWithAnd = true;
22649     } else
22650       SetCC = SetCC.getOperand(0);
22651   }
22652
22653   switch (SetCC.getOpcode()) {
22654   case X86ISD::SETCC_CARRY:
22655     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22656     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22657     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22658     // truncated to i1 using 'and'.
22659     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22660       break;
22661     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22662            "Invalid use of SETCC_CARRY!");
22663     // FALL THROUGH
22664   case X86ISD::SETCC:
22665     // Set the condition code or opposite one if necessary.
22666     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22667     if (needOppositeCond)
22668       CC = X86::GetOppositeBranchCondition(CC);
22669     return SetCC.getOperand(1);
22670   case X86ISD::CMOV: {
22671     // Check whether false/true value has canonical one, i.e. 0 or 1.
22672     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22673     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22674     // Quit if true value is not a constant.
22675     if (!TVal)
22676       return SDValue();
22677     // Quit if false value is not a constant.
22678     if (!FVal) {
22679       SDValue Op = SetCC.getOperand(0);
22680       // Skip 'zext' or 'trunc' node.
22681       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22682           Op.getOpcode() == ISD::TRUNCATE)
22683         Op = Op.getOperand(0);
22684       // A special case for rdrand/rdseed, where 0 is set if false cond is
22685       // found.
22686       if ((Op.getOpcode() != X86ISD::RDRAND &&
22687            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22688         return SDValue();
22689     }
22690     // Quit if false value is not the constant 0 or 1.
22691     bool FValIsFalse = true;
22692     if (FVal && FVal->getZExtValue() != 0) {
22693       if (FVal->getZExtValue() != 1)
22694         return SDValue();
22695       // If FVal is 1, opposite cond is needed.
22696       needOppositeCond = !needOppositeCond;
22697       FValIsFalse = false;
22698     }
22699     // Quit if TVal is not the constant opposite of FVal.
22700     if (FValIsFalse && TVal->getZExtValue() != 1)
22701       return SDValue();
22702     if (!FValIsFalse && TVal->getZExtValue() != 0)
22703       return SDValue();
22704     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22705     if (needOppositeCond)
22706       CC = X86::GetOppositeBranchCondition(CC);
22707     return SetCC.getOperand(3);
22708   }
22709   }
22710
22711   return SDValue();
22712 }
22713
22714 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22715 /// Match:
22716 ///   (X86or (X86setcc) (X86setcc))
22717 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22718 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22719                                            X86::CondCode &CC1, SDValue &Flags,
22720                                            bool &isAnd) {
22721   if (Cond->getOpcode() == X86ISD::CMP) {
22722     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22723     if (!CondOp1C || !CondOp1C->isNullValue())
22724       return false;
22725
22726     Cond = Cond->getOperand(0);
22727   }
22728
22729   isAnd = false;
22730
22731   SDValue SetCC0, SetCC1;
22732   switch (Cond->getOpcode()) {
22733   default: return false;
22734   case ISD::AND:
22735   case X86ISD::AND:
22736     isAnd = true;
22737     // fallthru
22738   case ISD::OR:
22739   case X86ISD::OR:
22740     SetCC0 = Cond->getOperand(0);
22741     SetCC1 = Cond->getOperand(1);
22742     break;
22743   };
22744
22745   // Make sure we have SETCC nodes, using the same flags value.
22746   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22747       SetCC1.getOpcode() != X86ISD::SETCC ||
22748       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22749     return false;
22750
22751   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22752   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22753   Flags = SetCC0->getOperand(1);
22754   return true;
22755 }
22756
22757 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22758 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22759                                   TargetLowering::DAGCombinerInfo &DCI,
22760                                   const X86Subtarget *Subtarget) {
22761   SDLoc DL(N);
22762
22763   // If the flag operand isn't dead, don't touch this CMOV.
22764   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22765     return SDValue();
22766
22767   SDValue FalseOp = N->getOperand(0);
22768   SDValue TrueOp = N->getOperand(1);
22769   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22770   SDValue Cond = N->getOperand(3);
22771
22772   if (CC == X86::COND_E || CC == X86::COND_NE) {
22773     switch (Cond.getOpcode()) {
22774     default: break;
22775     case X86ISD::BSR:
22776     case X86ISD::BSF:
22777       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22778       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22779         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22780     }
22781   }
22782
22783   SDValue Flags;
22784
22785   Flags = checkBoolTestSetCCCombine(Cond, CC);
22786   if (Flags.getNode() &&
22787       // Extra check as FCMOV only supports a subset of X86 cond.
22788       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22789     SDValue Ops[] = { FalseOp, TrueOp,
22790                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22791     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22792   }
22793
22794   // If this is a select between two integer constants, try to do some
22795   // optimizations.  Note that the operands are ordered the opposite of SELECT
22796   // operands.
22797   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22798     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22799       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22800       // larger than FalseC (the false value).
22801       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22802         CC = X86::GetOppositeBranchCondition(CC);
22803         std::swap(TrueC, FalseC);
22804         std::swap(TrueOp, FalseOp);
22805       }
22806
22807       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22808       // This is efficient for any integer data type (including i8/i16) and
22809       // shift amount.
22810       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22811         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22812                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22813
22814         // Zero extend the condition if needed.
22815         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22816
22817         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22818         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22819                            DAG.getConstant(ShAmt, DL, MVT::i8));
22820         if (N->getNumValues() == 2)  // Dead flag value?
22821           return DCI.CombineTo(N, Cond, SDValue());
22822         return Cond;
22823       }
22824
22825       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22826       // for any integer data type, including i8/i16.
22827       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22828         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22829                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22830
22831         // Zero extend the condition if needed.
22832         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22833                            FalseC->getValueType(0), Cond);
22834         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22835                            SDValue(FalseC, 0));
22836
22837         if (N->getNumValues() == 2)  // Dead flag value?
22838           return DCI.CombineTo(N, Cond, SDValue());
22839         return Cond;
22840       }
22841
22842       // Optimize cases that will turn into an LEA instruction.  This requires
22843       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22844       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22845         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22846         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22847
22848         bool isFastMultiplier = false;
22849         if (Diff < 10) {
22850           switch ((unsigned char)Diff) {
22851           default: break;
22852           case 1:  // result = add base, cond
22853           case 2:  // result = lea base(    , cond*2)
22854           case 3:  // result = lea base(cond, cond*2)
22855           case 4:  // result = lea base(    , cond*4)
22856           case 5:  // result = lea base(cond, cond*4)
22857           case 8:  // result = lea base(    , cond*8)
22858           case 9:  // result = lea base(cond, cond*8)
22859             isFastMultiplier = true;
22860             break;
22861           }
22862         }
22863
22864         if (isFastMultiplier) {
22865           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22866           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22867                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22868           // Zero extend the condition if needed.
22869           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22870                              Cond);
22871           // Scale the condition by the difference.
22872           if (Diff != 1)
22873             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22874                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22875
22876           // Add the base if non-zero.
22877           if (FalseC->getAPIntValue() != 0)
22878             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22879                                SDValue(FalseC, 0));
22880           if (N->getNumValues() == 2)  // Dead flag value?
22881             return DCI.CombineTo(N, Cond, SDValue());
22882           return Cond;
22883         }
22884       }
22885     }
22886   }
22887
22888   // Handle these cases:
22889   //   (select (x != c), e, c) -> select (x != c), e, x),
22890   //   (select (x == c), c, e) -> select (x == c), x, e)
22891   // where the c is an integer constant, and the "select" is the combination
22892   // of CMOV and CMP.
22893   //
22894   // The rationale for this change is that the conditional-move from a constant
22895   // needs two instructions, however, conditional-move from a register needs
22896   // only one instruction.
22897   //
22898   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22899   //  some instruction-combining opportunities. This opt needs to be
22900   //  postponed as late as possible.
22901   //
22902   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22903     // the DCI.xxxx conditions are provided to postpone the optimization as
22904     // late as possible.
22905
22906     ConstantSDNode *CmpAgainst = nullptr;
22907     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22908         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22909         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22910
22911       if (CC == X86::COND_NE &&
22912           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22913         CC = X86::GetOppositeBranchCondition(CC);
22914         std::swap(TrueOp, FalseOp);
22915       }
22916
22917       if (CC == X86::COND_E &&
22918           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22919         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22920                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22921         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22922       }
22923     }
22924   }
22925
22926   // Fold and/or of setcc's to double CMOV:
22927   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22928   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22929   //
22930   // This combine lets us generate:
22931   //   cmovcc1 (jcc1 if we don't have CMOV)
22932   //   cmovcc2 (same)
22933   // instead of:
22934   //   setcc1
22935   //   setcc2
22936   //   and/or
22937   //   cmovne (jne if we don't have CMOV)
22938   // When we can't use the CMOV instruction, it might increase branch
22939   // mispredicts.
22940   // When we can use CMOV, or when there is no mispredict, this improves
22941   // throughput and reduces register pressure.
22942   //
22943   if (CC == X86::COND_NE) {
22944     SDValue Flags;
22945     X86::CondCode CC0, CC1;
22946     bool isAndSetCC;
22947     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22948       if (isAndSetCC) {
22949         std::swap(FalseOp, TrueOp);
22950         CC0 = X86::GetOppositeBranchCondition(CC0);
22951         CC1 = X86::GetOppositeBranchCondition(CC1);
22952       }
22953
22954       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22955         Flags};
22956       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22957       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22958       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22959       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22960       return CMOV;
22961     }
22962   }
22963
22964   return SDValue();
22965 }
22966
22967 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22968                                                 const X86Subtarget *Subtarget) {
22969   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22970   switch (IntNo) {
22971   default: return SDValue();
22972   // SSE/AVX/AVX2 blend intrinsics.
22973   case Intrinsic::x86_avx2_pblendvb:
22974     // Don't try to simplify this intrinsic if we don't have AVX2.
22975     if (!Subtarget->hasAVX2())
22976       return SDValue();
22977     // FALL-THROUGH
22978   case Intrinsic::x86_avx_blendv_pd_256:
22979   case Intrinsic::x86_avx_blendv_ps_256:
22980     // Don't try to simplify this intrinsic if we don't have AVX.
22981     if (!Subtarget->hasAVX())
22982       return SDValue();
22983     // FALL-THROUGH
22984   case Intrinsic::x86_sse41_blendvps:
22985   case Intrinsic::x86_sse41_blendvpd:
22986   case Intrinsic::x86_sse41_pblendvb: {
22987     SDValue Op0 = N->getOperand(1);
22988     SDValue Op1 = N->getOperand(2);
22989     SDValue Mask = N->getOperand(3);
22990
22991     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22992     if (!Subtarget->hasSSE41())
22993       return SDValue();
22994
22995     // fold (blend A, A, Mask) -> A
22996     if (Op0 == Op1)
22997       return Op0;
22998     // fold (blend A, B, allZeros) -> A
22999     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23000       return Op0;
23001     // fold (blend A, B, allOnes) -> B
23002     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23003       return Op1;
23004
23005     // Simplify the case where the mask is a constant i32 value.
23006     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23007       if (C->isNullValue())
23008         return Op0;
23009       if (C->isAllOnesValue())
23010         return Op1;
23011     }
23012
23013     return SDValue();
23014   }
23015
23016   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23017   case Intrinsic::x86_sse2_psrai_w:
23018   case Intrinsic::x86_sse2_psrai_d:
23019   case Intrinsic::x86_avx2_psrai_w:
23020   case Intrinsic::x86_avx2_psrai_d:
23021   case Intrinsic::x86_sse2_psra_w:
23022   case Intrinsic::x86_sse2_psra_d:
23023   case Intrinsic::x86_avx2_psra_w:
23024   case Intrinsic::x86_avx2_psra_d: {
23025     SDValue Op0 = N->getOperand(1);
23026     SDValue Op1 = N->getOperand(2);
23027     EVT VT = Op0.getValueType();
23028     assert(VT.isVector() && "Expected a vector type!");
23029
23030     if (isa<BuildVectorSDNode>(Op1))
23031       Op1 = Op1.getOperand(0);
23032
23033     if (!isa<ConstantSDNode>(Op1))
23034       return SDValue();
23035
23036     EVT SVT = VT.getVectorElementType();
23037     unsigned SVTBits = SVT.getSizeInBits();
23038
23039     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23040     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23041     uint64_t ShAmt = C.getZExtValue();
23042
23043     // Don't try to convert this shift into a ISD::SRA if the shift
23044     // count is bigger than or equal to the element size.
23045     if (ShAmt >= SVTBits)
23046       return SDValue();
23047
23048     // Trivial case: if the shift count is zero, then fold this
23049     // into the first operand.
23050     if (ShAmt == 0)
23051       return Op0;
23052
23053     // Replace this packed shift intrinsic with a target independent
23054     // shift dag node.
23055     SDLoc DL(N);
23056     SDValue Splat = DAG.getConstant(C, DL, VT);
23057     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23058   }
23059   }
23060 }
23061
23062 /// PerformMulCombine - Optimize a single multiply with constant into two
23063 /// in order to implement it with two cheaper instructions, e.g.
23064 /// LEA + SHL, LEA + LEA.
23065 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23066                                  TargetLowering::DAGCombinerInfo &DCI) {
23067   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23068     return SDValue();
23069
23070   EVT VT = N->getValueType(0);
23071   if (VT != MVT::i64 && VT != MVT::i32)
23072     return SDValue();
23073
23074   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23075   if (!C)
23076     return SDValue();
23077   uint64_t MulAmt = C->getZExtValue();
23078   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23079     return SDValue();
23080
23081   uint64_t MulAmt1 = 0;
23082   uint64_t MulAmt2 = 0;
23083   if ((MulAmt % 9) == 0) {
23084     MulAmt1 = 9;
23085     MulAmt2 = MulAmt / 9;
23086   } else if ((MulAmt % 5) == 0) {
23087     MulAmt1 = 5;
23088     MulAmt2 = MulAmt / 5;
23089   } else if ((MulAmt % 3) == 0) {
23090     MulAmt1 = 3;
23091     MulAmt2 = MulAmt / 3;
23092   }
23093   if (MulAmt2 &&
23094       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23095     SDLoc DL(N);
23096
23097     if (isPowerOf2_64(MulAmt2) &&
23098         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23099       // If second multiplifer is pow2, issue it first. We want the multiply by
23100       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23101       // is an add.
23102       std::swap(MulAmt1, MulAmt2);
23103
23104     SDValue NewMul;
23105     if (isPowerOf2_64(MulAmt1))
23106       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23107                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23108     else
23109       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23110                            DAG.getConstant(MulAmt1, DL, VT));
23111
23112     if (isPowerOf2_64(MulAmt2))
23113       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23114                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23115     else
23116       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23117                            DAG.getConstant(MulAmt2, DL, VT));
23118
23119     // Do not add new nodes to DAG combiner worklist.
23120     DCI.CombineTo(N, NewMul, false);
23121   }
23122   return SDValue();
23123 }
23124
23125 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23126   SDValue N0 = N->getOperand(0);
23127   SDValue N1 = N->getOperand(1);
23128   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23129   EVT VT = N0.getValueType();
23130
23131   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23132   // since the result of setcc_c is all zero's or all ones.
23133   if (VT.isInteger() && !VT.isVector() &&
23134       N1C && N0.getOpcode() == ISD::AND &&
23135       N0.getOperand(1).getOpcode() == ISD::Constant) {
23136     SDValue N00 = N0.getOperand(0);
23137     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23138         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23139           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23140          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23141       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23142       APInt ShAmt = N1C->getAPIntValue();
23143       Mask = Mask.shl(ShAmt);
23144       if (Mask != 0) {
23145         SDLoc DL(N);
23146         return DAG.getNode(ISD::AND, DL, VT,
23147                            N00, DAG.getConstant(Mask, DL, VT));
23148       }
23149     }
23150   }
23151
23152   // Hardware support for vector shifts is sparse which makes us scalarize the
23153   // vector operations in many cases. Also, on sandybridge ADD is faster than
23154   // shl.
23155   // (shl V, 1) -> add V,V
23156   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23157     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23158       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23159       // We shift all of the values by one. In many cases we do not have
23160       // hardware support for this operation. This is better expressed as an ADD
23161       // of two values.
23162       if (N1SplatC->getZExtValue() == 1)
23163         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23164     }
23165
23166   return SDValue();
23167 }
23168
23169 /// \brief Returns a vector of 0s if the node in input is a vector logical
23170 /// shift by a constant amount which is known to be bigger than or equal
23171 /// to the vector element size in bits.
23172 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23173                                       const X86Subtarget *Subtarget) {
23174   EVT VT = N->getValueType(0);
23175
23176   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23177       (!Subtarget->hasInt256() ||
23178        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23179     return SDValue();
23180
23181   SDValue Amt = N->getOperand(1);
23182   SDLoc DL(N);
23183   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23184     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23185       APInt ShiftAmt = AmtSplat->getAPIntValue();
23186       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23187
23188       // SSE2/AVX2 logical shifts always return a vector of 0s
23189       // if the shift amount is bigger than or equal to
23190       // the element size. The constant shift amount will be
23191       // encoded as a 8-bit immediate.
23192       if (ShiftAmt.trunc(8).uge(MaxAmount))
23193         return getZeroVector(VT, Subtarget, DAG, DL);
23194     }
23195
23196   return SDValue();
23197 }
23198
23199 /// PerformShiftCombine - Combine shifts.
23200 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23201                                    TargetLowering::DAGCombinerInfo &DCI,
23202                                    const X86Subtarget *Subtarget) {
23203   if (N->getOpcode() == ISD::SHL)
23204     if (SDValue V = PerformSHLCombine(N, DAG))
23205       return V;
23206
23207   // Try to fold this logical shift into a zero vector.
23208   if (N->getOpcode() != ISD::SRA)
23209     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23210       return V;
23211
23212   return SDValue();
23213 }
23214
23215 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23216 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23217 // and friends.  Likewise for OR -> CMPNEQSS.
23218 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23219                             TargetLowering::DAGCombinerInfo &DCI,
23220                             const X86Subtarget *Subtarget) {
23221   unsigned opcode;
23222
23223   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23224   // we're requiring SSE2 for both.
23225   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23226     SDValue N0 = N->getOperand(0);
23227     SDValue N1 = N->getOperand(1);
23228     SDValue CMP0 = N0->getOperand(1);
23229     SDValue CMP1 = N1->getOperand(1);
23230     SDLoc DL(N);
23231
23232     // The SETCCs should both refer to the same CMP.
23233     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23234       return SDValue();
23235
23236     SDValue CMP00 = CMP0->getOperand(0);
23237     SDValue CMP01 = CMP0->getOperand(1);
23238     EVT     VT    = CMP00.getValueType();
23239
23240     if (VT == MVT::f32 || VT == MVT::f64) {
23241       bool ExpectingFlags = false;
23242       // Check for any users that want flags:
23243       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23244            !ExpectingFlags && UI != UE; ++UI)
23245         switch (UI->getOpcode()) {
23246         default:
23247         case ISD::BR_CC:
23248         case ISD::BRCOND:
23249         case ISD::SELECT:
23250           ExpectingFlags = true;
23251           break;
23252         case ISD::CopyToReg:
23253         case ISD::SIGN_EXTEND:
23254         case ISD::ZERO_EXTEND:
23255         case ISD::ANY_EXTEND:
23256           break;
23257         }
23258
23259       if (!ExpectingFlags) {
23260         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23261         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23262
23263         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23264           X86::CondCode tmp = cc0;
23265           cc0 = cc1;
23266           cc1 = tmp;
23267         }
23268
23269         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23270             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23271           // FIXME: need symbolic constants for these magic numbers.
23272           // See X86ATTInstPrinter.cpp:printSSECC().
23273           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23274           if (Subtarget->hasAVX512()) {
23275             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23276                                          CMP01,
23277                                          DAG.getConstant(x86cc, DL, MVT::i8));
23278             if (N->getValueType(0) != MVT::i1)
23279               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23280                                  FSetCC);
23281             return FSetCC;
23282           }
23283           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23284                                               CMP00.getValueType(), CMP00, CMP01,
23285                                               DAG.getConstant(x86cc, DL,
23286                                                               MVT::i8));
23287
23288           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23289           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23290
23291           if (is64BitFP && !Subtarget->is64Bit()) {
23292             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23293             // 64-bit integer, since that's not a legal type. Since
23294             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23295             // bits, but can do this little dance to extract the lowest 32 bits
23296             // and work with those going forward.
23297             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23298                                            OnesOrZeroesF);
23299             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23300             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23301                                         Vector32, DAG.getIntPtrConstant(0, DL));
23302             IntVT = MVT::i32;
23303           }
23304
23305           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23306           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23307                                       DAG.getConstant(1, DL, IntVT));
23308           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23309                                               ANDed);
23310           return OneBitOfTruth;
23311         }
23312       }
23313     }
23314   }
23315   return SDValue();
23316 }
23317
23318 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23319 /// so it can be folded inside ANDNP.
23320 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23321   EVT VT = N->getValueType(0);
23322
23323   // Match direct AllOnes for 128 and 256-bit vectors
23324   if (ISD::isBuildVectorAllOnes(N))
23325     return true;
23326
23327   // Look through a bit convert.
23328   if (N->getOpcode() == ISD::BITCAST)
23329     N = N->getOperand(0).getNode();
23330
23331   // Sometimes the operand may come from a insert_subvector building a 256-bit
23332   // allones vector
23333   if (VT.is256BitVector() &&
23334       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23335     SDValue V1 = N->getOperand(0);
23336     SDValue V2 = N->getOperand(1);
23337
23338     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23339         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23340         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23341         ISD::isBuildVectorAllOnes(V2.getNode()))
23342       return true;
23343   }
23344
23345   return false;
23346 }
23347
23348 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23349 // register. In most cases we actually compare or select YMM-sized registers
23350 // and mixing the two types creates horrible code. This method optimizes
23351 // some of the transition sequences.
23352 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23353                                  TargetLowering::DAGCombinerInfo &DCI,
23354                                  const X86Subtarget *Subtarget) {
23355   EVT VT = N->getValueType(0);
23356   if (!VT.is256BitVector())
23357     return SDValue();
23358
23359   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23360           N->getOpcode() == ISD::ZERO_EXTEND ||
23361           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23362
23363   SDValue Narrow = N->getOperand(0);
23364   EVT NarrowVT = Narrow->getValueType(0);
23365   if (!NarrowVT.is128BitVector())
23366     return SDValue();
23367
23368   if (Narrow->getOpcode() != ISD::XOR &&
23369       Narrow->getOpcode() != ISD::AND &&
23370       Narrow->getOpcode() != ISD::OR)
23371     return SDValue();
23372
23373   SDValue N0  = Narrow->getOperand(0);
23374   SDValue N1  = Narrow->getOperand(1);
23375   SDLoc DL(Narrow);
23376
23377   // The Left side has to be a trunc.
23378   if (N0.getOpcode() != ISD::TRUNCATE)
23379     return SDValue();
23380
23381   // The type of the truncated inputs.
23382   EVT WideVT = N0->getOperand(0)->getValueType(0);
23383   if (WideVT != VT)
23384     return SDValue();
23385
23386   // The right side has to be a 'trunc' or a constant vector.
23387   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23388   ConstantSDNode *RHSConstSplat = nullptr;
23389   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23390     RHSConstSplat = RHSBV->getConstantSplatNode();
23391   if (!RHSTrunc && !RHSConstSplat)
23392     return SDValue();
23393
23394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23395
23396   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23397     return SDValue();
23398
23399   // Set N0 and N1 to hold the inputs to the new wide operation.
23400   N0 = N0->getOperand(0);
23401   if (RHSConstSplat) {
23402     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23403                      SDValue(RHSConstSplat, 0));
23404     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23405     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23406   } else if (RHSTrunc) {
23407     N1 = N1->getOperand(0);
23408   }
23409
23410   // Generate the wide operation.
23411   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23412   unsigned Opcode = N->getOpcode();
23413   switch (Opcode) {
23414   case ISD::ANY_EXTEND:
23415     return Op;
23416   case ISD::ZERO_EXTEND: {
23417     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23418     APInt Mask = APInt::getAllOnesValue(InBits);
23419     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23420     return DAG.getNode(ISD::AND, DL, VT,
23421                        Op, DAG.getConstant(Mask, DL, VT));
23422   }
23423   case ISD::SIGN_EXTEND:
23424     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23425                        Op, DAG.getValueType(NarrowVT));
23426   default:
23427     llvm_unreachable("Unexpected opcode");
23428   }
23429 }
23430
23431 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23432                                  TargetLowering::DAGCombinerInfo &DCI,
23433                                  const X86Subtarget *Subtarget) {
23434   SDValue N0 = N->getOperand(0);
23435   SDValue N1 = N->getOperand(1);
23436   SDLoc DL(N);
23437
23438   // A vector zext_in_reg may be represented as a shuffle,
23439   // feeding into a bitcast (this represents anyext) feeding into
23440   // an and with a mask.
23441   // We'd like to try to combine that into a shuffle with zero
23442   // plus a bitcast, removing the and.
23443   if (N0.getOpcode() != ISD::BITCAST ||
23444       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23445     return SDValue();
23446
23447   // The other side of the AND should be a splat of 2^C, where C
23448   // is the number of bits in the source type.
23449   if (N1.getOpcode() == ISD::BITCAST)
23450     N1 = N1.getOperand(0);
23451   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23452     return SDValue();
23453   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23454
23455   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23456   EVT SrcType = Shuffle->getValueType(0);
23457
23458   // We expect a single-source shuffle
23459   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23460     return SDValue();
23461
23462   unsigned SrcSize = SrcType.getScalarSizeInBits();
23463
23464   APInt SplatValue, SplatUndef;
23465   unsigned SplatBitSize;
23466   bool HasAnyUndefs;
23467   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23468                                 SplatBitSize, HasAnyUndefs))
23469     return SDValue();
23470
23471   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23472   // Make sure the splat matches the mask we expect
23473   if (SplatBitSize > ResSize ||
23474       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23475     return SDValue();
23476
23477   // Make sure the input and output size make sense
23478   if (SrcSize >= ResSize || ResSize % SrcSize)
23479     return SDValue();
23480
23481   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23482   // The number of u's between each two values depends on the ratio between
23483   // the source and dest type.
23484   unsigned ZextRatio = ResSize / SrcSize;
23485   bool IsZext = true;
23486   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23487     if (i % ZextRatio) {
23488       if (Shuffle->getMaskElt(i) > 0) {
23489         // Expected undef
23490         IsZext = false;
23491         break;
23492       }
23493     } else {
23494       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23495         // Expected element number
23496         IsZext = false;
23497         break;
23498       }
23499     }
23500   }
23501
23502   if (!IsZext)
23503     return SDValue();
23504
23505   // Ok, perform the transformation - replace the shuffle with
23506   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23507   // (instead of undef) where the k elements come from the zero vector.
23508   SmallVector<int, 8> Mask;
23509   unsigned NumElems = SrcType.getVectorNumElements();
23510   for (unsigned i = 0; i < NumElems; ++i)
23511     if (i % ZextRatio)
23512       Mask.push_back(NumElems);
23513     else
23514       Mask.push_back(i / ZextRatio);
23515
23516   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23517     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23518   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23519 }
23520
23521 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23522                                  TargetLowering::DAGCombinerInfo &DCI,
23523                                  const X86Subtarget *Subtarget) {
23524   if (DCI.isBeforeLegalizeOps())
23525     return SDValue();
23526
23527   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23528     return Zext;
23529
23530   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23531     return R;
23532
23533   EVT VT = N->getValueType(0);
23534   SDValue N0 = N->getOperand(0);
23535   SDValue N1 = N->getOperand(1);
23536   SDLoc DL(N);
23537
23538   // Create BEXTR instructions
23539   // BEXTR is ((X >> imm) & (2**size-1))
23540   if (VT == MVT::i32 || VT == MVT::i64) {
23541     // Check for BEXTR.
23542     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23543         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23544       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23545       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23546       if (MaskNode && ShiftNode) {
23547         uint64_t Mask = MaskNode->getZExtValue();
23548         uint64_t Shift = ShiftNode->getZExtValue();
23549         if (isMask_64(Mask)) {
23550           uint64_t MaskSize = countPopulation(Mask);
23551           if (Shift + MaskSize <= VT.getSizeInBits())
23552             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23553                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23554                                                VT));
23555         }
23556       }
23557     } // BEXTR
23558
23559     return SDValue();
23560   }
23561
23562   // Want to form ANDNP nodes:
23563   // 1) In the hopes of then easily combining them with OR and AND nodes
23564   //    to form PBLEND/PSIGN.
23565   // 2) To match ANDN packed intrinsics
23566   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23567     return SDValue();
23568
23569   // Check LHS for vnot
23570   if (N0.getOpcode() == ISD::XOR &&
23571       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23572       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23573     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23574
23575   // Check RHS for vnot
23576   if (N1.getOpcode() == ISD::XOR &&
23577       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23578       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23579     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23580
23581   return SDValue();
23582 }
23583
23584 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23585                                 TargetLowering::DAGCombinerInfo &DCI,
23586                                 const X86Subtarget *Subtarget) {
23587   if (DCI.isBeforeLegalizeOps())
23588     return SDValue();
23589
23590   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23591     return R;
23592
23593   SDValue N0 = N->getOperand(0);
23594   SDValue N1 = N->getOperand(1);
23595   EVT VT = N->getValueType(0);
23596
23597   // look for psign/blend
23598   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23599     if (!Subtarget->hasSSSE3() ||
23600         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23601       return SDValue();
23602
23603     // Canonicalize pandn to RHS
23604     if (N0.getOpcode() == X86ISD::ANDNP)
23605       std::swap(N0, N1);
23606     // or (and (m, y), (pandn m, x))
23607     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23608       SDValue Mask = N1.getOperand(0);
23609       SDValue X    = N1.getOperand(1);
23610       SDValue Y;
23611       if (N0.getOperand(0) == Mask)
23612         Y = N0.getOperand(1);
23613       if (N0.getOperand(1) == Mask)
23614         Y = N0.getOperand(0);
23615
23616       // Check to see if the mask appeared in both the AND and ANDNP and
23617       if (!Y.getNode())
23618         return SDValue();
23619
23620       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23621       // Look through mask bitcast.
23622       if (Mask.getOpcode() == ISD::BITCAST)
23623         Mask = Mask.getOperand(0);
23624       if (X.getOpcode() == ISD::BITCAST)
23625         X = X.getOperand(0);
23626       if (Y.getOpcode() == ISD::BITCAST)
23627         Y = Y.getOperand(0);
23628
23629       EVT MaskVT = Mask.getValueType();
23630
23631       // Validate that the Mask operand is a vector sra node.
23632       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23633       // there is no psrai.b
23634       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23635       unsigned SraAmt = ~0;
23636       if (Mask.getOpcode() == ISD::SRA) {
23637         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23638           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23639             SraAmt = AmtConst->getZExtValue();
23640       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23641         SDValue SraC = Mask.getOperand(1);
23642         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23643       }
23644       if ((SraAmt + 1) != EltBits)
23645         return SDValue();
23646
23647       SDLoc DL(N);
23648
23649       // Now we know we at least have a plendvb with the mask val.  See if
23650       // we can form a psignb/w/d.
23651       // psign = x.type == y.type == mask.type && y = sub(0, x);
23652       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23653           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23654           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23655         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23656                "Unsupported VT for PSIGN");
23657         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23658         return DAG.getBitcast(VT, Mask);
23659       }
23660       // PBLENDVB only available on SSE 4.1
23661       if (!Subtarget->hasSSE41())
23662         return SDValue();
23663
23664       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23665
23666       X = DAG.getBitcast(BlendVT, X);
23667       Y = DAG.getBitcast(BlendVT, Y);
23668       Mask = DAG.getBitcast(BlendVT, Mask);
23669       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23670       return DAG.getBitcast(VT, Mask);
23671     }
23672   }
23673
23674   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23675     return SDValue();
23676
23677   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23678   MachineFunction &MF = DAG.getMachineFunction();
23679   bool OptForSize =
23680       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23681
23682   // SHLD/SHRD instructions have lower register pressure, but on some
23683   // platforms they have higher latency than the equivalent
23684   // series of shifts/or that would otherwise be generated.
23685   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23686   // have higher latencies and we are not optimizing for size.
23687   if (!OptForSize && Subtarget->isSHLDSlow())
23688     return SDValue();
23689
23690   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23691     std::swap(N0, N1);
23692   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23693     return SDValue();
23694   if (!N0.hasOneUse() || !N1.hasOneUse())
23695     return SDValue();
23696
23697   SDValue ShAmt0 = N0.getOperand(1);
23698   if (ShAmt0.getValueType() != MVT::i8)
23699     return SDValue();
23700   SDValue ShAmt1 = N1.getOperand(1);
23701   if (ShAmt1.getValueType() != MVT::i8)
23702     return SDValue();
23703   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23704     ShAmt0 = ShAmt0.getOperand(0);
23705   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23706     ShAmt1 = ShAmt1.getOperand(0);
23707
23708   SDLoc DL(N);
23709   unsigned Opc = X86ISD::SHLD;
23710   SDValue Op0 = N0.getOperand(0);
23711   SDValue Op1 = N1.getOperand(0);
23712   if (ShAmt0.getOpcode() == ISD::SUB) {
23713     Opc = X86ISD::SHRD;
23714     std::swap(Op0, Op1);
23715     std::swap(ShAmt0, ShAmt1);
23716   }
23717
23718   unsigned Bits = VT.getSizeInBits();
23719   if (ShAmt1.getOpcode() == ISD::SUB) {
23720     SDValue Sum = ShAmt1.getOperand(0);
23721     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23722       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23723       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23724         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23725       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23726         return DAG.getNode(Opc, DL, VT,
23727                            Op0, Op1,
23728                            DAG.getNode(ISD::TRUNCATE, DL,
23729                                        MVT::i8, ShAmt0));
23730     }
23731   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23732     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23733     if (ShAmt0C &&
23734         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23735       return DAG.getNode(Opc, DL, VT,
23736                          N0.getOperand(0), N1.getOperand(0),
23737                          DAG.getNode(ISD::TRUNCATE, DL,
23738                                        MVT::i8, ShAmt0));
23739   }
23740
23741   return SDValue();
23742 }
23743
23744 // Generate NEG and CMOV for integer abs.
23745 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23746   EVT VT = N->getValueType(0);
23747
23748   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23749   // 8-bit integer abs to NEG and CMOV.
23750   if (VT.isInteger() && VT.getSizeInBits() == 8)
23751     return SDValue();
23752
23753   SDValue N0 = N->getOperand(0);
23754   SDValue N1 = N->getOperand(1);
23755   SDLoc DL(N);
23756
23757   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23758   // and change it to SUB and CMOV.
23759   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23760       N0.getOpcode() == ISD::ADD &&
23761       N0.getOperand(1) == N1 &&
23762       N1.getOpcode() == ISD::SRA &&
23763       N1.getOperand(0) == N0.getOperand(0))
23764     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23765       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23766         // Generate SUB & CMOV.
23767         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23768                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23769
23770         SDValue Ops[] = { N0.getOperand(0), Neg,
23771                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23772                           SDValue(Neg.getNode(), 1) };
23773         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23774       }
23775   return SDValue();
23776 }
23777
23778 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23779 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23780                                  TargetLowering::DAGCombinerInfo &DCI,
23781                                  const X86Subtarget *Subtarget) {
23782   if (DCI.isBeforeLegalizeOps())
23783     return SDValue();
23784
23785   if (Subtarget->hasCMov())
23786     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23787       return RV;
23788
23789   return SDValue();
23790 }
23791
23792 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23793 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23794                                   TargetLowering::DAGCombinerInfo &DCI,
23795                                   const X86Subtarget *Subtarget) {
23796   LoadSDNode *Ld = cast<LoadSDNode>(N);
23797   EVT RegVT = Ld->getValueType(0);
23798   EVT MemVT = Ld->getMemoryVT();
23799   SDLoc dl(Ld);
23800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23801
23802   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23803   // into two 16-byte operations.
23804   ISD::LoadExtType Ext = Ld->getExtensionType();
23805   unsigned Alignment = Ld->getAlignment();
23806   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23807   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23808       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23809     unsigned NumElems = RegVT.getVectorNumElements();
23810     if (NumElems < 2)
23811       return SDValue();
23812
23813     SDValue Ptr = Ld->getBasePtr();
23814     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23815
23816     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23817                                   NumElems/2);
23818     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23819                                 Ld->getPointerInfo(), Ld->isVolatile(),
23820                                 Ld->isNonTemporal(), Ld->isInvariant(),
23821                                 Alignment);
23822     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23823     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23824                                 Ld->getPointerInfo(), Ld->isVolatile(),
23825                                 Ld->isNonTemporal(), Ld->isInvariant(),
23826                                 std::min(16U, Alignment));
23827     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23828                              Load1.getValue(1),
23829                              Load2.getValue(1));
23830
23831     SDValue NewVec = DAG.getUNDEF(RegVT);
23832     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23833     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23834     return DCI.CombineTo(N, NewVec, TF, true);
23835   }
23836
23837   return SDValue();
23838 }
23839
23840 /// PerformMLOADCombine - Resolve extending loads
23841 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23842                                    TargetLowering::DAGCombinerInfo &DCI,
23843                                    const X86Subtarget *Subtarget) {
23844   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23845   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23846     return SDValue();
23847
23848   EVT VT = Mld->getValueType(0);
23849   unsigned NumElems = VT.getVectorNumElements();
23850   EVT LdVT = Mld->getMemoryVT();
23851   SDLoc dl(Mld);
23852
23853   assert(LdVT != VT && "Cannot extend to the same type");
23854   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23855   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23856   // From, To sizes and ElemCount must be pow of two
23857   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23858     "Unexpected size for extending masked load");
23859
23860   unsigned SizeRatio  = ToSz / FromSz;
23861   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23862
23863   // Create a type on which we perform the shuffle
23864   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23865           LdVT.getScalarType(), NumElems*SizeRatio);
23866   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23867
23868   // Convert Src0 value
23869   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
23870   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23871     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23872     for (unsigned i = 0; i != NumElems; ++i)
23873       ShuffleVec[i] = i * SizeRatio;
23874
23875     // Can't shuffle using an illegal type.
23876     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23877             && "WideVecVT should be legal");
23878     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23879                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23880   }
23881   // Prepare the new mask
23882   SDValue NewMask;
23883   SDValue Mask = Mld->getMask();
23884   if (Mask.getValueType() == VT) {
23885     // Mask and original value have the same type
23886     NewMask = DAG.getBitcast(WideVecVT, Mask);
23887     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23888     for (unsigned i = 0; i != NumElems; ++i)
23889       ShuffleVec[i] = i * SizeRatio;
23890     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23891       ShuffleVec[i] = NumElems*SizeRatio;
23892     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23893                                    DAG.getConstant(0, dl, WideVecVT),
23894                                    &ShuffleVec[0]);
23895   }
23896   else {
23897     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23898     unsigned WidenNumElts = NumElems*SizeRatio;
23899     unsigned MaskNumElts = VT.getVectorNumElements();
23900     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23901                                      WidenNumElts);
23902
23903     unsigned NumConcat = WidenNumElts / MaskNumElts;
23904     SmallVector<SDValue, 16> Ops(NumConcat);
23905     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23906     Ops[0] = Mask;
23907     for (unsigned i = 1; i != NumConcat; ++i)
23908       Ops[i] = ZeroVal;
23909
23910     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23911   }
23912
23913   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23914                                      Mld->getBasePtr(), NewMask, WideSrc0,
23915                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23916                                      ISD::NON_EXTLOAD);
23917   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23918   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23919
23920 }
23921 /// PerformMSTORECombine - Resolve truncating stores
23922 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23923                                     const X86Subtarget *Subtarget) {
23924   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23925   if (!Mst->isTruncatingStore())
23926     return SDValue();
23927
23928   EVT VT = Mst->getValue().getValueType();
23929   unsigned NumElems = VT.getVectorNumElements();
23930   EVT StVT = Mst->getMemoryVT();
23931   SDLoc dl(Mst);
23932
23933   assert(StVT != VT && "Cannot truncate to the same type");
23934   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23935   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23936
23937   // From, To sizes and ElemCount must be pow of two
23938   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23939     "Unexpected size for truncating masked store");
23940   // We are going to use the original vector elt for storing.
23941   // Accumulated smaller vector elements must be a multiple of the store size.
23942   assert (((NumElems * FromSz) % ToSz) == 0 &&
23943           "Unexpected ratio for truncating masked store");
23944
23945   unsigned SizeRatio  = FromSz / ToSz;
23946   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23947
23948   // Create a type on which we perform the shuffle
23949   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23950           StVT.getScalarType(), NumElems*SizeRatio);
23951
23952   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23953
23954   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
23955   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23956   for (unsigned i = 0; i != NumElems; ++i)
23957     ShuffleVec[i] = i * SizeRatio;
23958
23959   // Can't shuffle using an illegal type.
23960   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23961           && "WideVecVT should be legal");
23962
23963   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23964                                         DAG.getUNDEF(WideVecVT),
23965                                         &ShuffleVec[0]);
23966
23967   SDValue NewMask;
23968   SDValue Mask = Mst->getMask();
23969   if (Mask.getValueType() == VT) {
23970     // Mask and original value have the same type
23971     NewMask = DAG.getBitcast(WideVecVT, Mask);
23972     for (unsigned i = 0; i != NumElems; ++i)
23973       ShuffleVec[i] = i * SizeRatio;
23974     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23975       ShuffleVec[i] = NumElems*SizeRatio;
23976     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23977                                    DAG.getConstant(0, dl, WideVecVT),
23978                                    &ShuffleVec[0]);
23979   }
23980   else {
23981     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23982     unsigned WidenNumElts = NumElems*SizeRatio;
23983     unsigned MaskNumElts = VT.getVectorNumElements();
23984     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23985                                      WidenNumElts);
23986
23987     unsigned NumConcat = WidenNumElts / MaskNumElts;
23988     SmallVector<SDValue, 16> Ops(NumConcat);
23989     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23990     Ops[0] = Mask;
23991     for (unsigned i = 1; i != NumConcat; ++i)
23992       Ops[i] = ZeroVal;
23993
23994     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23995   }
23996
23997   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23998                             NewMask, StVT, Mst->getMemOperand(), false);
23999 }
24000 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24001 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24002                                    const X86Subtarget *Subtarget) {
24003   StoreSDNode *St = cast<StoreSDNode>(N);
24004   EVT VT = St->getValue().getValueType();
24005   EVT StVT = St->getMemoryVT();
24006   SDLoc dl(St);
24007   SDValue StoredVal = St->getOperand(1);
24008   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24009
24010   // If we are saving a concatenation of two XMM registers and 32-byte stores
24011   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24012   unsigned Alignment = St->getAlignment();
24013   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24014   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24015       StVT == VT && !IsAligned) {
24016     unsigned NumElems = VT.getVectorNumElements();
24017     if (NumElems < 2)
24018       return SDValue();
24019
24020     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24021     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24022
24023     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
24024     SDValue Ptr0 = St->getBasePtr();
24025     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24026
24027     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24028                                 St->getPointerInfo(), St->isVolatile(),
24029                                 St->isNonTemporal(), Alignment);
24030     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24031                                 St->getPointerInfo(), St->isVolatile(),
24032                                 St->isNonTemporal(),
24033                                 std::min(16U, Alignment));
24034     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24035   }
24036
24037   // Optimize trunc store (of multiple scalars) to shuffle and store.
24038   // First, pack all of the elements in one place. Next, store to memory
24039   // in fewer chunks.
24040   if (St->isTruncatingStore() && VT.isVector()) {
24041     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24042     unsigned NumElems = VT.getVectorNumElements();
24043     assert(StVT != VT && "Cannot truncate to the same type");
24044     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24045     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24046
24047     // From, To sizes and ElemCount must be pow of two
24048     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24049     // We are going to use the original vector elt for storing.
24050     // Accumulated smaller vector elements must be a multiple of the store size.
24051     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24052
24053     unsigned SizeRatio  = FromSz / ToSz;
24054
24055     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24056
24057     // Create a type on which we perform the shuffle
24058     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24059             StVT.getScalarType(), NumElems*SizeRatio);
24060
24061     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24062
24063     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24064     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24065     for (unsigned i = 0; i != NumElems; ++i)
24066       ShuffleVec[i] = i * SizeRatio;
24067
24068     // Can't shuffle using an illegal type.
24069     if (!TLI.isTypeLegal(WideVecVT))
24070       return SDValue();
24071
24072     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24073                                          DAG.getUNDEF(WideVecVT),
24074                                          &ShuffleVec[0]);
24075     // At this point all of the data is stored at the bottom of the
24076     // register. We now need to save it to mem.
24077
24078     // Find the largest store unit
24079     MVT StoreType = MVT::i8;
24080     for (MVT Tp : MVT::integer_valuetypes()) {
24081       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24082         StoreType = Tp;
24083     }
24084
24085     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24086     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24087         (64 <= NumElems * ToSz))
24088       StoreType = MVT::f64;
24089
24090     // Bitcast the original vector into a vector of store-size units
24091     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24092             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24093     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24094     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24095     SmallVector<SDValue, 8> Chains;
24096     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
24097                                         TLI.getPointerTy());
24098     SDValue Ptr = St->getBasePtr();
24099
24100     // Perform one or more big stores into memory.
24101     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24102       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24103                                    StoreType, ShuffWide,
24104                                    DAG.getIntPtrConstant(i, dl));
24105       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24106                                 St->getPointerInfo(), St->isVolatile(),
24107                                 St->isNonTemporal(), St->getAlignment());
24108       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24109       Chains.push_back(Ch);
24110     }
24111
24112     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24113   }
24114
24115   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24116   // the FP state in cases where an emms may be missing.
24117   // A preferable solution to the general problem is to figure out the right
24118   // places to insert EMMS.  This qualifies as a quick hack.
24119
24120   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24121   if (VT.getSizeInBits() != 64)
24122     return SDValue();
24123
24124   const Function *F = DAG.getMachineFunction().getFunction();
24125   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24126   bool F64IsLegal =
24127       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24128   if ((VT.isVector() ||
24129        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24130       isa<LoadSDNode>(St->getValue()) &&
24131       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24132       St->getChain().hasOneUse() && !St->isVolatile()) {
24133     SDNode* LdVal = St->getValue().getNode();
24134     LoadSDNode *Ld = nullptr;
24135     int TokenFactorIndex = -1;
24136     SmallVector<SDValue, 8> Ops;
24137     SDNode* ChainVal = St->getChain().getNode();
24138     // Must be a store of a load.  We currently handle two cases:  the load
24139     // is a direct child, and it's under an intervening TokenFactor.  It is
24140     // possible to dig deeper under nested TokenFactors.
24141     if (ChainVal == LdVal)
24142       Ld = cast<LoadSDNode>(St->getChain());
24143     else if (St->getValue().hasOneUse() &&
24144              ChainVal->getOpcode() == ISD::TokenFactor) {
24145       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24146         if (ChainVal->getOperand(i).getNode() == LdVal) {
24147           TokenFactorIndex = i;
24148           Ld = cast<LoadSDNode>(St->getValue());
24149         } else
24150           Ops.push_back(ChainVal->getOperand(i));
24151       }
24152     }
24153
24154     if (!Ld || !ISD::isNormalLoad(Ld))
24155       return SDValue();
24156
24157     // If this is not the MMX case, i.e. we are just turning i64 load/store
24158     // into f64 load/store, avoid the transformation if there are multiple
24159     // uses of the loaded value.
24160     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24161       return SDValue();
24162
24163     SDLoc LdDL(Ld);
24164     SDLoc StDL(N);
24165     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24166     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24167     // pair instead.
24168     if (Subtarget->is64Bit() || F64IsLegal) {
24169       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24170       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24171                                   Ld->getPointerInfo(), Ld->isVolatile(),
24172                                   Ld->isNonTemporal(), Ld->isInvariant(),
24173                                   Ld->getAlignment());
24174       SDValue NewChain = NewLd.getValue(1);
24175       if (TokenFactorIndex != -1) {
24176         Ops.push_back(NewChain);
24177         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24178       }
24179       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24180                           St->getPointerInfo(),
24181                           St->isVolatile(), St->isNonTemporal(),
24182                           St->getAlignment());
24183     }
24184
24185     // Otherwise, lower to two pairs of 32-bit loads / stores.
24186     SDValue LoAddr = Ld->getBasePtr();
24187     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24188                                  DAG.getConstant(4, LdDL, MVT::i32));
24189
24190     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24191                                Ld->getPointerInfo(),
24192                                Ld->isVolatile(), Ld->isNonTemporal(),
24193                                Ld->isInvariant(), Ld->getAlignment());
24194     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24195                                Ld->getPointerInfo().getWithOffset(4),
24196                                Ld->isVolatile(), Ld->isNonTemporal(),
24197                                Ld->isInvariant(),
24198                                MinAlign(Ld->getAlignment(), 4));
24199
24200     SDValue NewChain = LoLd.getValue(1);
24201     if (TokenFactorIndex != -1) {
24202       Ops.push_back(LoLd);
24203       Ops.push_back(HiLd);
24204       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24205     }
24206
24207     LoAddr = St->getBasePtr();
24208     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24209                          DAG.getConstant(4, StDL, MVT::i32));
24210
24211     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24212                                 St->getPointerInfo(),
24213                                 St->isVolatile(), St->isNonTemporal(),
24214                                 St->getAlignment());
24215     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24216                                 St->getPointerInfo().getWithOffset(4),
24217                                 St->isVolatile(),
24218                                 St->isNonTemporal(),
24219                                 MinAlign(St->getAlignment(), 4));
24220     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24221   }
24222
24223   // This is similar to the above case, but here we handle a scalar 64-bit
24224   // integer store that is extracted from a vector on a 32-bit target.
24225   // If we have SSE2, then we can treat it like a floating-point double
24226   // to get past legalization. The execution dependencies fixup pass will
24227   // choose the optimal machine instruction for the store if this really is
24228   // an integer or v2f32 rather than an f64.
24229   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24230       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24231     SDValue OldExtract = St->getOperand(1);
24232     SDValue ExtOp0 = OldExtract.getOperand(0);
24233     unsigned VecSize = ExtOp0.getValueSizeInBits();
24234     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24235     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24236     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24237                                      BitCast, OldExtract.getOperand(1));
24238     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24239                         St->getPointerInfo(), St->isVolatile(),
24240                         St->isNonTemporal(), St->getAlignment());
24241   }
24242
24243   return SDValue();
24244 }
24245
24246 /// Return 'true' if this vector operation is "horizontal"
24247 /// and return the operands for the horizontal operation in LHS and RHS.  A
24248 /// horizontal operation performs the binary operation on successive elements
24249 /// of its first operand, then on successive elements of its second operand,
24250 /// returning the resulting values in a vector.  For example, if
24251 ///   A = < float a0, float a1, float a2, float a3 >
24252 /// and
24253 ///   B = < float b0, float b1, float b2, float b3 >
24254 /// then the result of doing a horizontal operation on A and B is
24255 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24256 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24257 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24258 /// set to A, RHS to B, and the routine returns 'true'.
24259 /// Note that the binary operation should have the property that if one of the
24260 /// operands is UNDEF then the result is UNDEF.
24261 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24262   // Look for the following pattern: if
24263   //   A = < float a0, float a1, float a2, float a3 >
24264   //   B = < float b0, float b1, float b2, float b3 >
24265   // and
24266   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24267   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24268   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24269   // which is A horizontal-op B.
24270
24271   // At least one of the operands should be a vector shuffle.
24272   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24273       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24274     return false;
24275
24276   MVT VT = LHS.getSimpleValueType();
24277
24278   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24279          "Unsupported vector type for horizontal add/sub");
24280
24281   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24282   // operate independently on 128-bit lanes.
24283   unsigned NumElts = VT.getVectorNumElements();
24284   unsigned NumLanes = VT.getSizeInBits()/128;
24285   unsigned NumLaneElts = NumElts / NumLanes;
24286   assert((NumLaneElts % 2 == 0) &&
24287          "Vector type should have an even number of elements in each lane");
24288   unsigned HalfLaneElts = NumLaneElts/2;
24289
24290   // View LHS in the form
24291   //   LHS = VECTOR_SHUFFLE A, B, LMask
24292   // If LHS is not a shuffle then pretend it is the shuffle
24293   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24294   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24295   // type VT.
24296   SDValue A, B;
24297   SmallVector<int, 16> LMask(NumElts);
24298   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24299     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24300       A = LHS.getOperand(0);
24301     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24302       B = LHS.getOperand(1);
24303     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24304     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24305   } else {
24306     if (LHS.getOpcode() != ISD::UNDEF)
24307       A = LHS;
24308     for (unsigned i = 0; i != NumElts; ++i)
24309       LMask[i] = i;
24310   }
24311
24312   // Likewise, view RHS in the form
24313   //   RHS = VECTOR_SHUFFLE C, D, RMask
24314   SDValue C, D;
24315   SmallVector<int, 16> RMask(NumElts);
24316   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24317     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24318       C = RHS.getOperand(0);
24319     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24320       D = RHS.getOperand(1);
24321     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24322     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24323   } else {
24324     if (RHS.getOpcode() != ISD::UNDEF)
24325       C = RHS;
24326     for (unsigned i = 0; i != NumElts; ++i)
24327       RMask[i] = i;
24328   }
24329
24330   // Check that the shuffles are both shuffling the same vectors.
24331   if (!(A == C && B == D) && !(A == D && B == C))
24332     return false;
24333
24334   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24335   if (!A.getNode() && !B.getNode())
24336     return false;
24337
24338   // If A and B occur in reverse order in RHS, then "swap" them (which means
24339   // rewriting the mask).
24340   if (A != C)
24341     ShuffleVectorSDNode::commuteMask(RMask);
24342
24343   // At this point LHS and RHS are equivalent to
24344   //   LHS = VECTOR_SHUFFLE A, B, LMask
24345   //   RHS = VECTOR_SHUFFLE A, B, RMask
24346   // Check that the masks correspond to performing a horizontal operation.
24347   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24348     for (unsigned i = 0; i != NumLaneElts; ++i) {
24349       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24350
24351       // Ignore any UNDEF components.
24352       if (LIdx < 0 || RIdx < 0 ||
24353           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24354           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24355         continue;
24356
24357       // Check that successive elements are being operated on.  If not, this is
24358       // not a horizontal operation.
24359       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24360       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24361       if (!(LIdx == Index && RIdx == Index + 1) &&
24362           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24363         return false;
24364     }
24365   }
24366
24367   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24368   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24369   return true;
24370 }
24371
24372 /// Do target-specific dag combines on floating point adds.
24373 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24374                                   const X86Subtarget *Subtarget) {
24375   EVT VT = N->getValueType(0);
24376   SDValue LHS = N->getOperand(0);
24377   SDValue RHS = N->getOperand(1);
24378
24379   // Try to synthesize horizontal adds from adds of shuffles.
24380   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24381        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24382       isHorizontalBinOp(LHS, RHS, true))
24383     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24384   return SDValue();
24385 }
24386
24387 /// Do target-specific dag combines on floating point subs.
24388 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24389                                   const X86Subtarget *Subtarget) {
24390   EVT VT = N->getValueType(0);
24391   SDValue LHS = N->getOperand(0);
24392   SDValue RHS = N->getOperand(1);
24393
24394   // Try to synthesize horizontal subs from subs of shuffles.
24395   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24396        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24397       isHorizontalBinOp(LHS, RHS, false))
24398     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24399   return SDValue();
24400 }
24401
24402 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24403 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24404   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24405
24406   // F[X]OR(0.0, x) -> x
24407   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24408     if (C->getValueAPF().isPosZero())
24409       return N->getOperand(1);
24410
24411   // F[X]OR(x, 0.0) -> x
24412   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24413     if (C->getValueAPF().isPosZero())
24414       return N->getOperand(0);
24415   return SDValue();
24416 }
24417
24418 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24419 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24420   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24421
24422   // Only perform optimizations if UnsafeMath is used.
24423   if (!DAG.getTarget().Options.UnsafeFPMath)
24424     return SDValue();
24425
24426   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24427   // into FMINC and FMAXC, which are Commutative operations.
24428   unsigned NewOp = 0;
24429   switch (N->getOpcode()) {
24430     default: llvm_unreachable("unknown opcode");
24431     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24432     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24433   }
24434
24435   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24436                      N->getOperand(0), N->getOperand(1));
24437 }
24438
24439 /// Do target-specific dag combines on X86ISD::FAND nodes.
24440 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24441   // FAND(0.0, x) -> 0.0
24442   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24443     if (C->getValueAPF().isPosZero())
24444       return N->getOperand(0);
24445
24446   // FAND(x, 0.0) -> 0.0
24447   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24448     if (C->getValueAPF().isPosZero())
24449       return N->getOperand(1);
24450
24451   return SDValue();
24452 }
24453
24454 /// Do target-specific dag combines on X86ISD::FANDN nodes
24455 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24456   // FANDN(0.0, x) -> x
24457   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24458     if (C->getValueAPF().isPosZero())
24459       return N->getOperand(1);
24460
24461   // FANDN(x, 0.0) -> 0.0
24462   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24463     if (C->getValueAPF().isPosZero())
24464       return N->getOperand(1);
24465
24466   return SDValue();
24467 }
24468
24469 static SDValue PerformBTCombine(SDNode *N,
24470                                 SelectionDAG &DAG,
24471                                 TargetLowering::DAGCombinerInfo &DCI) {
24472   // BT ignores high bits in the bit index operand.
24473   SDValue Op1 = N->getOperand(1);
24474   if (Op1.hasOneUse()) {
24475     unsigned BitWidth = Op1.getValueSizeInBits();
24476     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24477     APInt KnownZero, KnownOne;
24478     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24479                                           !DCI.isBeforeLegalizeOps());
24480     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24481     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24482         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24483       DCI.CommitTargetLoweringOpt(TLO);
24484   }
24485   return SDValue();
24486 }
24487
24488 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24489   SDValue Op = N->getOperand(0);
24490   if (Op.getOpcode() == ISD::BITCAST)
24491     Op = Op.getOperand(0);
24492   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24493   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24494       VT.getVectorElementType().getSizeInBits() ==
24495       OpVT.getVectorElementType().getSizeInBits()) {
24496     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24497   }
24498   return SDValue();
24499 }
24500
24501 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24502                                                const X86Subtarget *Subtarget) {
24503   EVT VT = N->getValueType(0);
24504   if (!VT.isVector())
24505     return SDValue();
24506
24507   SDValue N0 = N->getOperand(0);
24508   SDValue N1 = N->getOperand(1);
24509   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24510   SDLoc dl(N);
24511
24512   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24513   // both SSE and AVX2 since there is no sign-extended shift right
24514   // operation on a vector with 64-bit elements.
24515   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24516   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24517   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24518       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24519     SDValue N00 = N0.getOperand(0);
24520
24521     // EXTLOAD has a better solution on AVX2,
24522     // it may be replaced with X86ISD::VSEXT node.
24523     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24524       if (!ISD::isNormalLoad(N00.getNode()))
24525         return SDValue();
24526
24527     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24528         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24529                                   N00, N1);
24530       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24531     }
24532   }
24533   return SDValue();
24534 }
24535
24536 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24537                                   TargetLowering::DAGCombinerInfo &DCI,
24538                                   const X86Subtarget *Subtarget) {
24539   SDValue N0 = N->getOperand(0);
24540   EVT VT = N->getValueType(0);
24541   EVT SVT = VT.getScalarType();
24542   EVT InVT = N0.getValueType();
24543   EVT InSVT = InVT.getScalarType();
24544   SDLoc DL(N);
24545
24546   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24547   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24548   // This exposes the sext to the sdivrem lowering, so that it directly extends
24549   // from AH (which we otherwise need to do contortions to access).
24550   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24551       InVT == MVT::i8 && VT == MVT::i32) {
24552     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24553     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24554                             N0.getOperand(0), N0.getOperand(1));
24555     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24556     return R.getValue(1);
24557   }
24558
24559   if (!DCI.isBeforeLegalizeOps()) {
24560     if (InVT == MVT::i1) {
24561       SDValue Zero = DAG.getConstant(0, DL, VT);
24562       SDValue AllOnes =
24563         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24564       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24565     }
24566     return SDValue();
24567   }
24568
24569   if (VT.isVector() && Subtarget->hasSSE2()) {
24570     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24571       EVT InVT = N.getValueType();
24572       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24573                                    Size / InVT.getScalarSizeInBits());
24574       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24575                                     DAG.getUNDEF(InVT));
24576       Opnds[0] = N;
24577       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24578     };
24579
24580     // If target-size is less than 128-bits, extend to a type that would extend
24581     // to 128 bits, extend that and extract the original target vector.
24582     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24583         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24584         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24585       unsigned Scale = 128 / VT.getSizeInBits();
24586       EVT ExVT =
24587           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24588       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24589       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24590       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24591                          DAG.getIntPtrConstant(0, DL));
24592     }
24593
24594     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24595     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24596     if (VT.getSizeInBits() == 128 &&
24597         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24598         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24599       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24600       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24601     }
24602
24603     // On pre-AVX2 targets, split into 128-bit nodes of
24604     // ISD::SIGN_EXTEND_VECTOR_INREG.
24605     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24606         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24607         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24608       unsigned NumVecs = VT.getSizeInBits() / 128;
24609       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24610       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24611       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24612
24613       SmallVector<SDValue, 8> Opnds;
24614       for (unsigned i = 0, Offset = 0; i != NumVecs;
24615            ++i, Offset += NumSubElts) {
24616         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24617                                      DAG.getIntPtrConstant(Offset, DL));
24618         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24619         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24620         Opnds.push_back(SrcVec);
24621       }
24622       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24623     }
24624   }
24625
24626   if (!Subtarget->hasFp256())
24627     return SDValue();
24628
24629   if (VT.isVector() && VT.getSizeInBits() == 256)
24630     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24631       return R;
24632
24633   return SDValue();
24634 }
24635
24636 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24637                                  const X86Subtarget* Subtarget) {
24638   SDLoc dl(N);
24639   EVT VT = N->getValueType(0);
24640
24641   // Let legalize expand this if it isn't a legal type yet.
24642   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24643     return SDValue();
24644
24645   EVT ScalarVT = VT.getScalarType();
24646   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24647       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24648        !Subtarget->hasAVX512()))
24649     return SDValue();
24650
24651   SDValue A = N->getOperand(0);
24652   SDValue B = N->getOperand(1);
24653   SDValue C = N->getOperand(2);
24654
24655   bool NegA = (A.getOpcode() == ISD::FNEG);
24656   bool NegB = (B.getOpcode() == ISD::FNEG);
24657   bool NegC = (C.getOpcode() == ISD::FNEG);
24658
24659   // Negative multiplication when NegA xor NegB
24660   bool NegMul = (NegA != NegB);
24661   if (NegA)
24662     A = A.getOperand(0);
24663   if (NegB)
24664     B = B.getOperand(0);
24665   if (NegC)
24666     C = C.getOperand(0);
24667
24668   unsigned Opcode;
24669   if (!NegMul)
24670     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24671   else
24672     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24673
24674   return DAG.getNode(Opcode, dl, VT, A, B, C);
24675 }
24676
24677 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24678                                   TargetLowering::DAGCombinerInfo &DCI,
24679                                   const X86Subtarget *Subtarget) {
24680   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24681   //           (and (i32 x86isd::setcc_carry), 1)
24682   // This eliminates the zext. This transformation is necessary because
24683   // ISD::SETCC is always legalized to i8.
24684   SDLoc dl(N);
24685   SDValue N0 = N->getOperand(0);
24686   EVT VT = N->getValueType(0);
24687
24688   if (N0.getOpcode() == ISD::AND &&
24689       N0.hasOneUse() &&
24690       N0.getOperand(0).hasOneUse()) {
24691     SDValue N00 = N0.getOperand(0);
24692     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24693       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24694       if (!C || C->getZExtValue() != 1)
24695         return SDValue();
24696       return DAG.getNode(ISD::AND, dl, VT,
24697                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24698                                      N00.getOperand(0), N00.getOperand(1)),
24699                          DAG.getConstant(1, dl, VT));
24700     }
24701   }
24702
24703   if (N0.getOpcode() == ISD::TRUNCATE &&
24704       N0.hasOneUse() &&
24705       N0.getOperand(0).hasOneUse()) {
24706     SDValue N00 = N0.getOperand(0);
24707     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24708       return DAG.getNode(ISD::AND, dl, VT,
24709                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24710                                      N00.getOperand(0), N00.getOperand(1)),
24711                          DAG.getConstant(1, dl, VT));
24712     }
24713   }
24714
24715   if (VT.is256BitVector())
24716     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24717       return R;
24718
24719   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24720   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24721   // This exposes the zext to the udivrem lowering, so that it directly extends
24722   // from AH (which we otherwise need to do contortions to access).
24723   if (N0.getOpcode() == ISD::UDIVREM &&
24724       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24725       (VT == MVT::i32 || VT == MVT::i64)) {
24726     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24727     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24728                             N0.getOperand(0), N0.getOperand(1));
24729     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24730     return R.getValue(1);
24731   }
24732
24733   return SDValue();
24734 }
24735
24736 // Optimize x == -y --> x+y == 0
24737 //          x != -y --> x+y != 0
24738 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24739                                       const X86Subtarget* Subtarget) {
24740   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24741   SDValue LHS = N->getOperand(0);
24742   SDValue RHS = N->getOperand(1);
24743   EVT VT = N->getValueType(0);
24744   SDLoc DL(N);
24745
24746   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24747     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24748       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24749         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24750                                    LHS.getOperand(1));
24751         return DAG.getSetCC(DL, N->getValueType(0), addV,
24752                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24753       }
24754   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24755     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24756       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24757         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24758                                    RHS.getOperand(1));
24759         return DAG.getSetCC(DL, N->getValueType(0), addV,
24760                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24761       }
24762
24763   if (VT.getScalarType() == MVT::i1 &&
24764       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24765     bool IsSEXT0 =
24766         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24767         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24768     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24769
24770     if (!IsSEXT0 || !IsVZero1) {
24771       // Swap the operands and update the condition code.
24772       std::swap(LHS, RHS);
24773       CC = ISD::getSetCCSwappedOperands(CC);
24774
24775       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24776                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24777       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24778     }
24779
24780     if (IsSEXT0 && IsVZero1) {
24781       assert(VT == LHS.getOperand(0).getValueType() &&
24782              "Uexpected operand type");
24783       if (CC == ISD::SETGT)
24784         return DAG.getConstant(0, DL, VT);
24785       if (CC == ISD::SETLE)
24786         return DAG.getConstant(1, DL, VT);
24787       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24788         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24789
24790       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24791              "Unexpected condition code!");
24792       return LHS.getOperand(0);
24793     }
24794   }
24795
24796   return SDValue();
24797 }
24798
24799 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24800                                          SelectionDAG &DAG) {
24801   SDLoc dl(Load);
24802   MVT VT = Load->getSimpleValueType(0);
24803   MVT EVT = VT.getVectorElementType();
24804   SDValue Addr = Load->getOperand(1);
24805   SDValue NewAddr = DAG.getNode(
24806       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24807       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24808                       Addr.getSimpleValueType()));
24809
24810   SDValue NewLoad =
24811       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24812                   DAG.getMachineFunction().getMachineMemOperand(
24813                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24814   return NewLoad;
24815 }
24816
24817 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24818                                       const X86Subtarget *Subtarget) {
24819   SDLoc dl(N);
24820   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24821   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24822          "X86insertps is only defined for v4x32");
24823
24824   SDValue Ld = N->getOperand(1);
24825   if (MayFoldLoad(Ld)) {
24826     // Extract the countS bits from the immediate so we can get the proper
24827     // address when narrowing the vector load to a specific element.
24828     // When the second source op is a memory address, insertps doesn't use
24829     // countS and just gets an f32 from that address.
24830     unsigned DestIndex =
24831         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24832
24833     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24834
24835     // Create this as a scalar to vector to match the instruction pattern.
24836     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24837     // countS bits are ignored when loading from memory on insertps, which
24838     // means we don't need to explicitly set them to 0.
24839     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24840                        LoadScalarToVector, N->getOperand(2));
24841   }
24842   return SDValue();
24843 }
24844
24845 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24846   SDValue V0 = N->getOperand(0);
24847   SDValue V1 = N->getOperand(1);
24848   SDLoc DL(N);
24849   EVT VT = N->getValueType(0);
24850
24851   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24852   // operands and changing the mask to 1. This saves us a bunch of
24853   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24854   // x86InstrInfo knows how to commute this back after instruction selection
24855   // if it would help register allocation.
24856
24857   // TODO: If optimizing for size or a processor that doesn't suffer from
24858   // partial register update stalls, this should be transformed into a MOVSD
24859   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24860
24861   if (VT == MVT::v2f64)
24862     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24863       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24864         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24865         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24866       }
24867
24868   return SDValue();
24869 }
24870
24871 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24872 // as "sbb reg,reg", since it can be extended without zext and produces
24873 // an all-ones bit which is more useful than 0/1 in some cases.
24874 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24875                                MVT VT) {
24876   if (VT == MVT::i8)
24877     return DAG.getNode(ISD::AND, DL, VT,
24878                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24879                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24880                                    EFLAGS),
24881                        DAG.getConstant(1, DL, VT));
24882   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24883   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24884                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24885                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24886                                  EFLAGS));
24887 }
24888
24889 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24890 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24891                                    TargetLowering::DAGCombinerInfo &DCI,
24892                                    const X86Subtarget *Subtarget) {
24893   SDLoc DL(N);
24894   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24895   SDValue EFLAGS = N->getOperand(1);
24896
24897   if (CC == X86::COND_A) {
24898     // Try to convert COND_A into COND_B in an attempt to facilitate
24899     // materializing "setb reg".
24900     //
24901     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24902     // cannot take an immediate as its first operand.
24903     //
24904     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24905         EFLAGS.getValueType().isInteger() &&
24906         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24907       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24908                                    EFLAGS.getNode()->getVTList(),
24909                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24910       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24911       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24912     }
24913   }
24914
24915   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24916   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24917   // cases.
24918   if (CC == X86::COND_B)
24919     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24920
24921   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24922     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24923     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24924   }
24925
24926   return SDValue();
24927 }
24928
24929 // Optimize branch condition evaluation.
24930 //
24931 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24932                                     TargetLowering::DAGCombinerInfo &DCI,
24933                                     const X86Subtarget *Subtarget) {
24934   SDLoc DL(N);
24935   SDValue Chain = N->getOperand(0);
24936   SDValue Dest = N->getOperand(1);
24937   SDValue EFLAGS = N->getOperand(3);
24938   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24939
24940   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24941     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24942     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24943                        Flags);
24944   }
24945
24946   return SDValue();
24947 }
24948
24949 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24950                                                          SelectionDAG &DAG) {
24951   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24952   // optimize away operation when it's from a constant.
24953   //
24954   // The general transformation is:
24955   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24956   //       AND(VECTOR_CMP(x,y), constant2)
24957   //    constant2 = UNARYOP(constant)
24958
24959   // Early exit if this isn't a vector operation, the operand of the
24960   // unary operation isn't a bitwise AND, or if the sizes of the operations
24961   // aren't the same.
24962   EVT VT = N->getValueType(0);
24963   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24964       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24965       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24966     return SDValue();
24967
24968   // Now check that the other operand of the AND is a constant. We could
24969   // make the transformation for non-constant splats as well, but it's unclear
24970   // that would be a benefit as it would not eliminate any operations, just
24971   // perform one more step in scalar code before moving to the vector unit.
24972   if (BuildVectorSDNode *BV =
24973           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24974     // Bail out if the vector isn't a constant.
24975     if (!BV->isConstant())
24976       return SDValue();
24977
24978     // Everything checks out. Build up the new and improved node.
24979     SDLoc DL(N);
24980     EVT IntVT = BV->getValueType(0);
24981     // Create a new constant of the appropriate type for the transformed
24982     // DAG.
24983     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24984     // The AND node needs bitcasts to/from an integer vector type around it.
24985     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
24986     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24987                                  N->getOperand(0)->getOperand(0), MaskConst);
24988     SDValue Res = DAG.getBitcast(VT, NewAnd);
24989     return Res;
24990   }
24991
24992   return SDValue();
24993 }
24994
24995 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24996                                         const X86Subtarget *Subtarget) {
24997   SDValue Op0 = N->getOperand(0);
24998   EVT VT = N->getValueType(0);
24999   EVT InVT = Op0.getValueType();
25000   EVT InSVT = InVT.getScalarType();
25001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25002
25003   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25004   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25005   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25006     SDLoc dl(N);
25007     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25008                                  InVT.getVectorNumElements());
25009     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25010
25011     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25012       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25013
25014     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25015   }
25016
25017   return SDValue();
25018 }
25019
25020 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25021                                         const X86Subtarget *Subtarget) {
25022   // First try to optimize away the conversion entirely when it's
25023   // conditionally from a constant. Vectors only.
25024   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25025     return Res;
25026
25027   // Now move on to more general possibilities.
25028   SDValue Op0 = N->getOperand(0);
25029   EVT VT = N->getValueType(0);
25030   EVT InVT = Op0.getValueType();
25031   EVT InSVT = InVT.getScalarType();
25032
25033   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25034   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25035   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25036     SDLoc dl(N);
25037     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25038                                  InVT.getVectorNumElements());
25039     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25040     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25041   }
25042
25043   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25044   // a 32-bit target where SSE doesn't support i64->FP operations.
25045   if (Op0.getOpcode() == ISD::LOAD) {
25046     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25047     EVT LdVT = Ld->getValueType(0);
25048
25049     // This transformation is not supported if the result type is f16
25050     if (VT == MVT::f16)
25051       return SDValue();
25052
25053     if (!Ld->isVolatile() && !VT.isVector() &&
25054         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25055         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25056       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25057           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25058       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25059       return FILDChain;
25060     }
25061   }
25062   return SDValue();
25063 }
25064
25065 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25066 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25067                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25068   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25069   // the result is either zero or one (depending on the input carry bit).
25070   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25071   if (X86::isZeroNode(N->getOperand(0)) &&
25072       X86::isZeroNode(N->getOperand(1)) &&
25073       // We don't have a good way to replace an EFLAGS use, so only do this when
25074       // dead right now.
25075       SDValue(N, 1).use_empty()) {
25076     SDLoc DL(N);
25077     EVT VT = N->getValueType(0);
25078     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25079     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25080                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25081                                            DAG.getConstant(X86::COND_B, DL,
25082                                                            MVT::i8),
25083                                            N->getOperand(2)),
25084                                DAG.getConstant(1, DL, VT));
25085     return DCI.CombineTo(N, Res1, CarryOut);
25086   }
25087
25088   return SDValue();
25089 }
25090
25091 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25092 //      (add Y, (setne X, 0)) -> sbb -1, Y
25093 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25094 //      (sub (setne X, 0), Y) -> adc -1, Y
25095 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25096   SDLoc DL(N);
25097
25098   // Look through ZExts.
25099   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25100   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25101     return SDValue();
25102
25103   SDValue SetCC = Ext.getOperand(0);
25104   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25105     return SDValue();
25106
25107   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25108   if (CC != X86::COND_E && CC != X86::COND_NE)
25109     return SDValue();
25110
25111   SDValue Cmp = SetCC.getOperand(1);
25112   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25113       !X86::isZeroNode(Cmp.getOperand(1)) ||
25114       !Cmp.getOperand(0).getValueType().isInteger())
25115     return SDValue();
25116
25117   SDValue CmpOp0 = Cmp.getOperand(0);
25118   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25119                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25120
25121   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25122   if (CC == X86::COND_NE)
25123     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25124                        DL, OtherVal.getValueType(), OtherVal,
25125                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25126                        NewCmp);
25127   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25128                      DL, OtherVal.getValueType(), OtherVal,
25129                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25130 }
25131
25132 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25133 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25134                                  const X86Subtarget *Subtarget) {
25135   EVT VT = N->getValueType(0);
25136   SDValue Op0 = N->getOperand(0);
25137   SDValue Op1 = N->getOperand(1);
25138
25139   // Try to synthesize horizontal adds from adds of shuffles.
25140   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25141        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25142       isHorizontalBinOp(Op0, Op1, true))
25143     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25144
25145   return OptimizeConditionalInDecrement(N, DAG);
25146 }
25147
25148 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25149                                  const X86Subtarget *Subtarget) {
25150   SDValue Op0 = N->getOperand(0);
25151   SDValue Op1 = N->getOperand(1);
25152
25153   // X86 can't encode an immediate LHS of a sub. See if we can push the
25154   // negation into a preceding instruction.
25155   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25156     // If the RHS of the sub is a XOR with one use and a constant, invert the
25157     // immediate. Then add one to the LHS of the sub so we can turn
25158     // X-Y -> X+~Y+1, saving one register.
25159     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25160         isa<ConstantSDNode>(Op1.getOperand(1))) {
25161       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25162       EVT VT = Op0.getValueType();
25163       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25164                                    Op1.getOperand(0),
25165                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25166       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25167                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25168     }
25169   }
25170
25171   // Try to synthesize horizontal adds from adds of shuffles.
25172   EVT VT = N->getValueType(0);
25173   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25174        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25175       isHorizontalBinOp(Op0, Op1, true))
25176     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25177
25178   return OptimizeConditionalInDecrement(N, DAG);
25179 }
25180
25181 /// performVZEXTCombine - Performs build vector combines
25182 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25183                                    TargetLowering::DAGCombinerInfo &DCI,
25184                                    const X86Subtarget *Subtarget) {
25185   SDLoc DL(N);
25186   MVT VT = N->getSimpleValueType(0);
25187   SDValue Op = N->getOperand(0);
25188   MVT OpVT = Op.getSimpleValueType();
25189   MVT OpEltVT = OpVT.getVectorElementType();
25190   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25191
25192   // (vzext (bitcast (vzext (x)) -> (vzext x)
25193   SDValue V = Op;
25194   while (V.getOpcode() == ISD::BITCAST)
25195     V = V.getOperand(0);
25196
25197   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25198     MVT InnerVT = V.getSimpleValueType();
25199     MVT InnerEltVT = InnerVT.getVectorElementType();
25200
25201     // If the element sizes match exactly, we can just do one larger vzext. This
25202     // is always an exact type match as vzext operates on integer types.
25203     if (OpEltVT == InnerEltVT) {
25204       assert(OpVT == InnerVT && "Types must match for vzext!");
25205       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25206     }
25207
25208     // The only other way we can combine them is if only a single element of the
25209     // inner vzext is used in the input to the outer vzext.
25210     if (InnerEltVT.getSizeInBits() < InputBits)
25211       return SDValue();
25212
25213     // In this case, the inner vzext is completely dead because we're going to
25214     // only look at bits inside of the low element. Just do the outer vzext on
25215     // a bitcast of the input to the inner.
25216     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25217   }
25218
25219   // Check if we can bypass extracting and re-inserting an element of an input
25220   // vector. Essentialy:
25221   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25222   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25223       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25224       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25225     SDValue ExtractedV = V.getOperand(0);
25226     SDValue OrigV = ExtractedV.getOperand(0);
25227     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25228       if (ExtractIdx->getZExtValue() == 0) {
25229         MVT OrigVT = OrigV.getSimpleValueType();
25230         // Extract a subvector if necessary...
25231         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25232           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25233           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25234                                     OrigVT.getVectorNumElements() / Ratio);
25235           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25236                               DAG.getIntPtrConstant(0, DL));
25237         }
25238         Op = DAG.getBitcast(OpVT, OrigV);
25239         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25240       }
25241   }
25242
25243   return SDValue();
25244 }
25245
25246 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25247                                              DAGCombinerInfo &DCI) const {
25248   SelectionDAG &DAG = DCI.DAG;
25249   switch (N->getOpcode()) {
25250   default: break;
25251   case ISD::EXTRACT_VECTOR_ELT:
25252     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25253   case ISD::VSELECT:
25254   case ISD::SELECT:
25255   case X86ISD::SHRUNKBLEND:
25256     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25257   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25258   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25259   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25260   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25261   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25262   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25263   case ISD::SHL:
25264   case ISD::SRA:
25265   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25266   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25267   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25268   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25269   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25270   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25271   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25272   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25273   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25274   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25275   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25276   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25277   case X86ISD::FXOR:
25278   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25279   case X86ISD::FMIN:
25280   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25281   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25282   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25283   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25284   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25285   case ISD::ANY_EXTEND:
25286   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25287   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25288   case ISD::SIGN_EXTEND_INREG:
25289     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25290   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25291   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25292   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25293   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25294   case X86ISD::SHUFP:       // Handle all target specific shuffles
25295   case X86ISD::PALIGNR:
25296   case X86ISD::UNPCKH:
25297   case X86ISD::UNPCKL:
25298   case X86ISD::MOVHLPS:
25299   case X86ISD::MOVLHPS:
25300   case X86ISD::PSHUFB:
25301   case X86ISD::PSHUFD:
25302   case X86ISD::PSHUFHW:
25303   case X86ISD::PSHUFLW:
25304   case X86ISD::MOVSS:
25305   case X86ISD::MOVSD:
25306   case X86ISD::VPERMILPI:
25307   case X86ISD::VPERM2X128:
25308   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25309   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25310   case ISD::INTRINSIC_WO_CHAIN:
25311     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25312   case X86ISD::INSERTPS: {
25313     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25314       return PerformINSERTPSCombine(N, DAG, Subtarget);
25315     break;
25316   }
25317   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25318   }
25319
25320   return SDValue();
25321 }
25322
25323 /// isTypeDesirableForOp - Return true if the target has native support for
25324 /// the specified value type and it is 'desirable' to use the type for the
25325 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25326 /// instruction encodings are longer and some i16 instructions are slow.
25327 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25328   if (!isTypeLegal(VT))
25329     return false;
25330   if (VT != MVT::i16)
25331     return true;
25332
25333   switch (Opc) {
25334   default:
25335     return true;
25336   case ISD::LOAD:
25337   case ISD::SIGN_EXTEND:
25338   case ISD::ZERO_EXTEND:
25339   case ISD::ANY_EXTEND:
25340   case ISD::SHL:
25341   case ISD::SRL:
25342   case ISD::SUB:
25343   case ISD::ADD:
25344   case ISD::MUL:
25345   case ISD::AND:
25346   case ISD::OR:
25347   case ISD::XOR:
25348     return false;
25349   }
25350 }
25351
25352 /// IsDesirableToPromoteOp - This method query the target whether it is
25353 /// beneficial for dag combiner to promote the specified node. If true, it
25354 /// should return the desired promotion type by reference.
25355 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25356   EVT VT = Op.getValueType();
25357   if (VT != MVT::i16)
25358     return false;
25359
25360   bool Promote = false;
25361   bool Commute = false;
25362   switch (Op.getOpcode()) {
25363   default: break;
25364   case ISD::LOAD: {
25365     LoadSDNode *LD = cast<LoadSDNode>(Op);
25366     // If the non-extending load has a single use and it's not live out, then it
25367     // might be folded.
25368     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25369                                                      Op.hasOneUse()*/) {
25370       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25371              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25372         // The only case where we'd want to promote LOAD (rather then it being
25373         // promoted as an operand is when it's only use is liveout.
25374         if (UI->getOpcode() != ISD::CopyToReg)
25375           return false;
25376       }
25377     }
25378     Promote = true;
25379     break;
25380   }
25381   case ISD::SIGN_EXTEND:
25382   case ISD::ZERO_EXTEND:
25383   case ISD::ANY_EXTEND:
25384     Promote = true;
25385     break;
25386   case ISD::SHL:
25387   case ISD::SRL: {
25388     SDValue N0 = Op.getOperand(0);
25389     // Look out for (store (shl (load), x)).
25390     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25391       return false;
25392     Promote = true;
25393     break;
25394   }
25395   case ISD::ADD:
25396   case ISD::MUL:
25397   case ISD::AND:
25398   case ISD::OR:
25399   case ISD::XOR:
25400     Commute = true;
25401     // fallthrough
25402   case ISD::SUB: {
25403     SDValue N0 = Op.getOperand(0);
25404     SDValue N1 = Op.getOperand(1);
25405     if (!Commute && MayFoldLoad(N1))
25406       return false;
25407     // Avoid disabling potential load folding opportunities.
25408     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25409       return false;
25410     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25411       return false;
25412     Promote = true;
25413   }
25414   }
25415
25416   PVT = MVT::i32;
25417   return Promote;
25418 }
25419
25420 //===----------------------------------------------------------------------===//
25421 //                           X86 Inline Assembly Support
25422 //===----------------------------------------------------------------------===//
25423
25424 // Helper to match a string separated by whitespace.
25425 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25426   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25427
25428   for (StringRef Piece : Pieces) {
25429     if (!S.startswith(Piece)) // Check if the piece matches.
25430       return false;
25431
25432     S = S.substr(Piece.size());
25433     StringRef::size_type Pos = S.find_first_not_of(" \t");
25434     if (Pos == 0) // We matched a prefix.
25435       return false;
25436
25437     S = S.substr(Pos);
25438   }
25439
25440   return S.empty();
25441 }
25442
25443 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25444
25445   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25446     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25447         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25448         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25449
25450       if (AsmPieces.size() == 3)
25451         return true;
25452       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25453         return true;
25454     }
25455   }
25456   return false;
25457 }
25458
25459 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25460   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25461
25462   std::string AsmStr = IA->getAsmString();
25463
25464   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25465   if (!Ty || Ty->getBitWidth() % 16 != 0)
25466     return false;
25467
25468   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25469   SmallVector<StringRef, 4> AsmPieces;
25470   SplitString(AsmStr, AsmPieces, ";\n");
25471
25472   switch (AsmPieces.size()) {
25473   default: return false;
25474   case 1:
25475     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25476     // we will turn this bswap into something that will be lowered to logical
25477     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25478     // lower so don't worry about this.
25479     // bswap $0
25480     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25481         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25482         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25483         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25484         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25485         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25486       // No need to check constraints, nothing other than the equivalent of
25487       // "=r,0" would be valid here.
25488       return IntrinsicLowering::LowerToByteSwap(CI);
25489     }
25490
25491     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25492     if (CI->getType()->isIntegerTy(16) &&
25493         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25494         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25495          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25496       AsmPieces.clear();
25497       StringRef ConstraintsStr = IA->getConstraintString();
25498       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25499       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25500       if (clobbersFlagRegisters(AsmPieces))
25501         return IntrinsicLowering::LowerToByteSwap(CI);
25502     }
25503     break;
25504   case 3:
25505     if (CI->getType()->isIntegerTy(32) &&
25506         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25507         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25508         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25509         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25510       AsmPieces.clear();
25511       StringRef ConstraintsStr = IA->getConstraintString();
25512       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25513       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25514       if (clobbersFlagRegisters(AsmPieces))
25515         return IntrinsicLowering::LowerToByteSwap(CI);
25516     }
25517
25518     if (CI->getType()->isIntegerTy(64)) {
25519       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25520       if (Constraints.size() >= 2 &&
25521           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25522           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25523         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25524         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25525             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25526             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25527           return IntrinsicLowering::LowerToByteSwap(CI);
25528       }
25529     }
25530     break;
25531   }
25532   return false;
25533 }
25534
25535 /// getConstraintType - Given a constraint letter, return the type of
25536 /// constraint it is for this target.
25537 X86TargetLowering::ConstraintType
25538 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25539   if (Constraint.size() == 1) {
25540     switch (Constraint[0]) {
25541     case 'R':
25542     case 'q':
25543     case 'Q':
25544     case 'f':
25545     case 't':
25546     case 'u':
25547     case 'y':
25548     case 'x':
25549     case 'Y':
25550     case 'l':
25551       return C_RegisterClass;
25552     case 'a':
25553     case 'b':
25554     case 'c':
25555     case 'd':
25556     case 'S':
25557     case 'D':
25558     case 'A':
25559       return C_Register;
25560     case 'I':
25561     case 'J':
25562     case 'K':
25563     case 'L':
25564     case 'M':
25565     case 'N':
25566     case 'G':
25567     case 'C':
25568     case 'e':
25569     case 'Z':
25570       return C_Other;
25571     default:
25572       break;
25573     }
25574   }
25575   return TargetLowering::getConstraintType(Constraint);
25576 }
25577
25578 /// Examine constraint type and operand type and determine a weight value.
25579 /// This object must already have been set up with the operand type
25580 /// and the current alternative constraint selected.
25581 TargetLowering::ConstraintWeight
25582   X86TargetLowering::getSingleConstraintMatchWeight(
25583     AsmOperandInfo &info, const char *constraint) const {
25584   ConstraintWeight weight = CW_Invalid;
25585   Value *CallOperandVal = info.CallOperandVal;
25586     // If we don't have a value, we can't do a match,
25587     // but allow it at the lowest weight.
25588   if (!CallOperandVal)
25589     return CW_Default;
25590   Type *type = CallOperandVal->getType();
25591   // Look at the constraint type.
25592   switch (*constraint) {
25593   default:
25594     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25595   case 'R':
25596   case 'q':
25597   case 'Q':
25598   case 'a':
25599   case 'b':
25600   case 'c':
25601   case 'd':
25602   case 'S':
25603   case 'D':
25604   case 'A':
25605     if (CallOperandVal->getType()->isIntegerTy())
25606       weight = CW_SpecificReg;
25607     break;
25608   case 'f':
25609   case 't':
25610   case 'u':
25611     if (type->isFloatingPointTy())
25612       weight = CW_SpecificReg;
25613     break;
25614   case 'y':
25615     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25616       weight = CW_SpecificReg;
25617     break;
25618   case 'x':
25619   case 'Y':
25620     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25621         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25622       weight = CW_Register;
25623     break;
25624   case 'I':
25625     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25626       if (C->getZExtValue() <= 31)
25627         weight = CW_Constant;
25628     }
25629     break;
25630   case 'J':
25631     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25632       if (C->getZExtValue() <= 63)
25633         weight = CW_Constant;
25634     }
25635     break;
25636   case 'K':
25637     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25638       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25639         weight = CW_Constant;
25640     }
25641     break;
25642   case 'L':
25643     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25644       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25645         weight = CW_Constant;
25646     }
25647     break;
25648   case 'M':
25649     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25650       if (C->getZExtValue() <= 3)
25651         weight = CW_Constant;
25652     }
25653     break;
25654   case 'N':
25655     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25656       if (C->getZExtValue() <= 0xff)
25657         weight = CW_Constant;
25658     }
25659     break;
25660   case 'G':
25661   case 'C':
25662     if (isa<ConstantFP>(CallOperandVal)) {
25663       weight = CW_Constant;
25664     }
25665     break;
25666   case 'e':
25667     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25668       if ((C->getSExtValue() >= -0x80000000LL) &&
25669           (C->getSExtValue() <= 0x7fffffffLL))
25670         weight = CW_Constant;
25671     }
25672     break;
25673   case 'Z':
25674     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25675       if (C->getZExtValue() <= 0xffffffff)
25676         weight = CW_Constant;
25677     }
25678     break;
25679   }
25680   return weight;
25681 }
25682
25683 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25684 /// with another that has more specific requirements based on the type of the
25685 /// corresponding operand.
25686 const char *X86TargetLowering::
25687 LowerXConstraint(EVT ConstraintVT) const {
25688   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25689   // 'f' like normal targets.
25690   if (ConstraintVT.isFloatingPoint()) {
25691     if (Subtarget->hasSSE2())
25692       return "Y";
25693     if (Subtarget->hasSSE1())
25694       return "x";
25695   }
25696
25697   return TargetLowering::LowerXConstraint(ConstraintVT);
25698 }
25699
25700 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25701 /// vector.  If it is invalid, don't add anything to Ops.
25702 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25703                                                      std::string &Constraint,
25704                                                      std::vector<SDValue>&Ops,
25705                                                      SelectionDAG &DAG) const {
25706   SDValue Result;
25707
25708   // Only support length 1 constraints for now.
25709   if (Constraint.length() > 1) return;
25710
25711   char ConstraintLetter = Constraint[0];
25712   switch (ConstraintLetter) {
25713   default: break;
25714   case 'I':
25715     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25716       if (C->getZExtValue() <= 31) {
25717         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25718                                        Op.getValueType());
25719         break;
25720       }
25721     }
25722     return;
25723   case 'J':
25724     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25725       if (C->getZExtValue() <= 63) {
25726         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25727                                        Op.getValueType());
25728         break;
25729       }
25730     }
25731     return;
25732   case 'K':
25733     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25734       if (isInt<8>(C->getSExtValue())) {
25735         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25736                                        Op.getValueType());
25737         break;
25738       }
25739     }
25740     return;
25741   case 'L':
25742     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25743       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25744           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25745         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25746                                        Op.getValueType());
25747         break;
25748       }
25749     }
25750     return;
25751   case 'M':
25752     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25753       if (C->getZExtValue() <= 3) {
25754         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25755                                        Op.getValueType());
25756         break;
25757       }
25758     }
25759     return;
25760   case 'N':
25761     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25762       if (C->getZExtValue() <= 255) {
25763         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25764                                        Op.getValueType());
25765         break;
25766       }
25767     }
25768     return;
25769   case 'O':
25770     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25771       if (C->getZExtValue() <= 127) {
25772         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25773                                        Op.getValueType());
25774         break;
25775       }
25776     }
25777     return;
25778   case 'e': {
25779     // 32-bit signed value
25780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25781       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25782                                            C->getSExtValue())) {
25783         // Widen to 64 bits here to get it sign extended.
25784         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25785         break;
25786       }
25787     // FIXME gcc accepts some relocatable values here too, but only in certain
25788     // memory models; it's complicated.
25789     }
25790     return;
25791   }
25792   case 'Z': {
25793     // 32-bit unsigned value
25794     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25795       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25796                                            C->getZExtValue())) {
25797         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25798                                        Op.getValueType());
25799         break;
25800       }
25801     }
25802     // FIXME gcc accepts some relocatable values here too, but only in certain
25803     // memory models; it's complicated.
25804     return;
25805   }
25806   case 'i': {
25807     // Literal immediates are always ok.
25808     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25809       // Widen to 64 bits here to get it sign extended.
25810       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25811       break;
25812     }
25813
25814     // In any sort of PIC mode addresses need to be computed at runtime by
25815     // adding in a register or some sort of table lookup.  These can't
25816     // be used as immediates.
25817     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25818       return;
25819
25820     // If we are in non-pic codegen mode, we allow the address of a global (with
25821     // an optional displacement) to be used with 'i'.
25822     GlobalAddressSDNode *GA = nullptr;
25823     int64_t Offset = 0;
25824
25825     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25826     while (1) {
25827       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25828         Offset += GA->getOffset();
25829         break;
25830       } else if (Op.getOpcode() == ISD::ADD) {
25831         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25832           Offset += C->getZExtValue();
25833           Op = Op.getOperand(0);
25834           continue;
25835         }
25836       } else if (Op.getOpcode() == ISD::SUB) {
25837         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25838           Offset += -C->getZExtValue();
25839           Op = Op.getOperand(0);
25840           continue;
25841         }
25842       }
25843
25844       // Otherwise, this isn't something we can handle, reject it.
25845       return;
25846     }
25847
25848     const GlobalValue *GV = GA->getGlobal();
25849     // If we require an extra load to get this address, as in PIC mode, we
25850     // can't accept it.
25851     if (isGlobalStubReference(
25852             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25853       return;
25854
25855     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25856                                         GA->getValueType(0), Offset);
25857     break;
25858   }
25859   }
25860
25861   if (Result.getNode()) {
25862     Ops.push_back(Result);
25863     return;
25864   }
25865   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25866 }
25867
25868 std::pair<unsigned, const TargetRegisterClass *>
25869 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25870                                                 StringRef Constraint,
25871                                                 MVT VT) const {
25872   // First, see if this is a constraint that directly corresponds to an LLVM
25873   // register class.
25874   if (Constraint.size() == 1) {
25875     // GCC Constraint Letters
25876     switch (Constraint[0]) {
25877     default: break;
25878       // TODO: Slight differences here in allocation order and leaving
25879       // RIP in the class. Do they matter any more here than they do
25880       // in the normal allocation?
25881     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25882       if (Subtarget->is64Bit()) {
25883         if (VT == MVT::i32 || VT == MVT::f32)
25884           return std::make_pair(0U, &X86::GR32RegClass);
25885         if (VT == MVT::i16)
25886           return std::make_pair(0U, &X86::GR16RegClass);
25887         if (VT == MVT::i8 || VT == MVT::i1)
25888           return std::make_pair(0U, &X86::GR8RegClass);
25889         if (VT == MVT::i64 || VT == MVT::f64)
25890           return std::make_pair(0U, &X86::GR64RegClass);
25891         break;
25892       }
25893       // 32-bit fallthrough
25894     case 'Q':   // Q_REGS
25895       if (VT == MVT::i32 || VT == MVT::f32)
25896         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25897       if (VT == MVT::i16)
25898         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25899       if (VT == MVT::i8 || VT == MVT::i1)
25900         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25901       if (VT == MVT::i64)
25902         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25903       break;
25904     case 'r':   // GENERAL_REGS
25905     case 'l':   // INDEX_REGS
25906       if (VT == MVT::i8 || VT == MVT::i1)
25907         return std::make_pair(0U, &X86::GR8RegClass);
25908       if (VT == MVT::i16)
25909         return std::make_pair(0U, &X86::GR16RegClass);
25910       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25911         return std::make_pair(0U, &X86::GR32RegClass);
25912       return std::make_pair(0U, &X86::GR64RegClass);
25913     case 'R':   // LEGACY_REGS
25914       if (VT == MVT::i8 || VT == MVT::i1)
25915         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25916       if (VT == MVT::i16)
25917         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25918       if (VT == MVT::i32 || !Subtarget->is64Bit())
25919         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25920       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25921     case 'f':  // FP Stack registers.
25922       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25923       // value to the correct fpstack register class.
25924       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25925         return std::make_pair(0U, &X86::RFP32RegClass);
25926       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25927         return std::make_pair(0U, &X86::RFP64RegClass);
25928       return std::make_pair(0U, &X86::RFP80RegClass);
25929     case 'y':   // MMX_REGS if MMX allowed.
25930       if (!Subtarget->hasMMX()) break;
25931       return std::make_pair(0U, &X86::VR64RegClass);
25932     case 'Y':   // SSE_REGS if SSE2 allowed
25933       if (!Subtarget->hasSSE2()) break;
25934       // FALL THROUGH.
25935     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25936       if (!Subtarget->hasSSE1()) break;
25937
25938       switch (VT.SimpleTy) {
25939       default: break;
25940       // Scalar SSE types.
25941       case MVT::f32:
25942       case MVT::i32:
25943         return std::make_pair(0U, &X86::FR32RegClass);
25944       case MVT::f64:
25945       case MVT::i64:
25946         return std::make_pair(0U, &X86::FR64RegClass);
25947       // Vector types.
25948       case MVT::v16i8:
25949       case MVT::v8i16:
25950       case MVT::v4i32:
25951       case MVT::v2i64:
25952       case MVT::v4f32:
25953       case MVT::v2f64:
25954         return std::make_pair(0U, &X86::VR128RegClass);
25955       // AVX types.
25956       case MVT::v32i8:
25957       case MVT::v16i16:
25958       case MVT::v8i32:
25959       case MVT::v4i64:
25960       case MVT::v8f32:
25961       case MVT::v4f64:
25962         return std::make_pair(0U, &X86::VR256RegClass);
25963       case MVT::v8f64:
25964       case MVT::v16f32:
25965       case MVT::v16i32:
25966       case MVT::v8i64:
25967         return std::make_pair(0U, &X86::VR512RegClass);
25968       }
25969       break;
25970     }
25971   }
25972
25973   // Use the default implementation in TargetLowering to convert the register
25974   // constraint into a member of a register class.
25975   std::pair<unsigned, const TargetRegisterClass*> Res;
25976   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25977
25978   // Not found as a standard register?
25979   if (!Res.second) {
25980     // Map st(0) -> st(7) -> ST0
25981     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25982         tolower(Constraint[1]) == 's' &&
25983         tolower(Constraint[2]) == 't' &&
25984         Constraint[3] == '(' &&
25985         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25986         Constraint[5] == ')' &&
25987         Constraint[6] == '}') {
25988
25989       Res.first = X86::FP0+Constraint[4]-'0';
25990       Res.second = &X86::RFP80RegClass;
25991       return Res;
25992     }
25993
25994     // GCC allows "st(0)" to be called just plain "st".
25995     if (StringRef("{st}").equals_lower(Constraint)) {
25996       Res.first = X86::FP0;
25997       Res.second = &X86::RFP80RegClass;
25998       return Res;
25999     }
26000
26001     // flags -> EFLAGS
26002     if (StringRef("{flags}").equals_lower(Constraint)) {
26003       Res.first = X86::EFLAGS;
26004       Res.second = &X86::CCRRegClass;
26005       return Res;
26006     }
26007
26008     // 'A' means EAX + EDX.
26009     if (Constraint == "A") {
26010       Res.first = X86::EAX;
26011       Res.second = &X86::GR32_ADRegClass;
26012       return Res;
26013     }
26014     return Res;
26015   }
26016
26017   // Otherwise, check to see if this is a register class of the wrong value
26018   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26019   // turn into {ax},{dx}.
26020   // MVT::Other is used to specify clobber names.
26021   if (Res.second->hasType(VT) || VT == MVT::Other)
26022     return Res;   // Correct type already, nothing to do.
26023
26024   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26025   // return "eax". This should even work for things like getting 64bit integer
26026   // registers when given an f64 type.
26027   const TargetRegisterClass *Class = Res.second;
26028   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26029       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26030     unsigned Size = VT.getSizeInBits();
26031     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26032                                   : Size == 16 ? MVT::i16
26033                                   : Size == 32 ? MVT::i32
26034                                   : Size == 64 ? MVT::i64
26035                                   : MVT::Other;
26036     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26037     if (DestReg > 0) {
26038       Res.first = DestReg;
26039       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26040                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26041                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26042                  : &X86::GR64RegClass;
26043       assert(Res.second->contains(Res.first) && "Register in register class");
26044     } else {
26045       // No register found/type mismatch.
26046       Res.first = 0;
26047       Res.second = nullptr;
26048     }
26049   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26050              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26051              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26052              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26053              Class == &X86::VR512RegClass) {
26054     // Handle references to XMM physical registers that got mapped into the
26055     // wrong class.  This can happen with constraints like {xmm0} where the
26056     // target independent register mapper will just pick the first match it can
26057     // find, ignoring the required type.
26058
26059     if (VT == MVT::f32 || VT == MVT::i32)
26060       Res.second = &X86::FR32RegClass;
26061     else if (VT == MVT::f64 || VT == MVT::i64)
26062       Res.second = &X86::FR64RegClass;
26063     else if (X86::VR128RegClass.hasType(VT))
26064       Res.second = &X86::VR128RegClass;
26065     else if (X86::VR256RegClass.hasType(VT))
26066       Res.second = &X86::VR256RegClass;
26067     else if (X86::VR512RegClass.hasType(VT))
26068       Res.second = &X86::VR512RegClass;
26069     else {
26070       // Type mismatch and not a clobber: Return an error;
26071       Res.first = 0;
26072       Res.second = nullptr;
26073     }
26074   }
26075
26076   return Res;
26077 }
26078
26079 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26080                                             Type *Ty,
26081                                             unsigned AS) const {
26082   // Scaling factors are not free at all.
26083   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26084   // will take 2 allocations in the out of order engine instead of 1
26085   // for plain addressing mode, i.e. inst (reg1).
26086   // E.g.,
26087   // vaddps (%rsi,%drx), %ymm0, %ymm1
26088   // Requires two allocations (one for the load, one for the computation)
26089   // whereas:
26090   // vaddps (%rsi), %ymm0, %ymm1
26091   // Requires just 1 allocation, i.e., freeing allocations for other operations
26092   // and having less micro operations to execute.
26093   //
26094   // For some X86 architectures, this is even worse because for instance for
26095   // stores, the complex addressing mode forces the instruction to use the
26096   // "load" ports instead of the dedicated "store" port.
26097   // E.g., on Haswell:
26098   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26099   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26100   if (isLegalAddressingMode(AM, Ty, AS))
26101     // Scale represents reg2 * scale, thus account for 1
26102     // as soon as we use a second register.
26103     return AM.Scale != 0;
26104   return -1;
26105 }
26106
26107 bool X86TargetLowering::isTargetFTOL() const {
26108   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26109 }