cc9374450cea98884f97d039216d78b887c33ede
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
72                        SDValue V2);
73
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75                                      const X86Subtarget &STI)
76     : TargetLowering(TM), Subtarget(&STI) {
77   X86ScalarSSEf64 = Subtarget->hasSSE2();
78   X86ScalarSSEf32 = Subtarget->hasSSE1();
79   TD = getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
209   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210   // are Legal, f80 is custom lowered.
211   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248   }
249
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1037   }
1038
1039   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1061     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1062     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1076
1077     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078     // even though v8i16 is a legal type.
1079     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1082
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1085     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1086
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1088     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1089
1090     for (MVT VT : MVT::fp_vector_valuetypes())
1091       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1092
1093     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1106
1107     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1109     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1110
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1128
1129     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1136     }
1137
1138     if (Subtarget->hasInt256()) {
1139       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1143
1144       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1148
1149       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1150       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1153
1154       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1156       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1157       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1158
1159       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1161       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1171
1172       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173       // when we have a 256bit-wide blend with immediate.
1174       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1175
1176       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1183
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1190     } else {
1191       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1195
1196       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1200
1201       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1205     }
1206
1207     // In the customized shift lowering, the legal cases in AVX2 will be
1208     // recognized.
1209     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1210     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1211
1212     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (MVT VT : MVT::vector_valuetypes()) {
1220       if (VT.getScalarSizeInBits() >= 32) {
1221         setOperationAction(ISD::MLOAD,  VT, Legal);
1222         setOperationAction(ISD::MSTORE, VT, Legal);
1223       }
1224       // Extract subvector is special because the value type
1225       // (result) is 128-bit but the source is 256-bit wide.
1226       if (VT.is128BitVector()) {
1227         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228       }
1229       // Do not attempt to custom lower other non-256-bit vectors
1230       if (!VT.is256BitVector())
1231         continue;
1232
1233       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1234       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1235       setOperationAction(ISD::VSELECT,            VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     if (Subtarget->hasInt256())
1244       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1245
1246
1247     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249       MVT VT = (MVT::SimpleValueType)i;
1250
1251       // Do not attempt to promote non-256-bit vectors
1252       if (!VT.is256BitVector())
1253         continue;
1254
1255       setOperationAction(ISD::AND,    VT, Promote);
1256       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1257       setOperationAction(ISD::OR,     VT, Promote);
1258       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1259       setOperationAction(ISD::XOR,    VT, Promote);
1260       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1261       setOperationAction(ISD::LOAD,   VT, Promote);
1262       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1263       setOperationAction(ISD::SELECT, VT, Promote);
1264       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265     }
1266   }
1267
1268   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1272     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1273
1274     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1275     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1276     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1277
1278     for (MVT VT : MVT::fp_vector_valuetypes())
1279       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1280
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1291     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1292     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1293
1294     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1295     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1296     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1297     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1298     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1299     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1300     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1301     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1302     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1305     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1306     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1307
1308     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1313     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1314
1315     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1321     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1323
1324     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1325     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1326     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1328     if (Subtarget->is64Bit()) {
1329       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1330       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1331       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1332       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1333     }
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1348     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1349     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1350
1351     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1352     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1353     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1354     if (Subtarget->hasDQI()) {
1355       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1356       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1357     }
1358     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1359     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1360     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1361     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1362     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1363     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1364     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1365     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1366     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1367     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1368     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1369     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1370     if (Subtarget->hasDQI()) {
1371       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1372       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1373     }
1374     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1375     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1376     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1377     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1378     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1379     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1380     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1381     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1382     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1383     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1384
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1390
1391     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1392     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1393
1394     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1395
1396     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1397     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1399     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1400     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1401     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1402     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1403     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1404     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1405     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1406     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1407
1408     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1409     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1410     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1411     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1412     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1413     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1414     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1415     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1416
1417     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1418     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1419
1420     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1421     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1422
1423     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1424
1425     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1426     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1427
1428     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1429     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1430
1431     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1432     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1433
1434     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1435     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1436     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1437     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1438     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1439     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1440
1441     if (Subtarget->hasCDI()) {
1442       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1443       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1444     }
1445     if (Subtarget->hasDQI()) {
1446       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1447       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1448       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1449     }
1450     // Custom lower several nodes.
1451     for (MVT VT : MVT::vector_valuetypes()) {
1452       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453       if (EltSize == 1) {
1454         setOperationAction(ISD::AND, VT, Legal);
1455         setOperationAction(ISD::OR,  VT, Legal);
1456         setOperationAction(ISD::XOR,  VT, Legal);
1457       }
1458       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1459         setOperationAction(ISD::MGATHER,  VT, Custom);
1460         setOperationAction(ISD::MSCATTER, VT, Custom);
1461       }
1462       // Extract subvector is special because the value type
1463       // (result) is 256/128-bit but the source is 512-bit wide.
1464       if (VT.is128BitVector() || VT.is256BitVector()) {
1465         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1466       }
1467       if (VT.getVectorElementType() == MVT::i1)
1468         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1469
1470       // Do not attempt to custom lower other non-512-bit vectors
1471       if (!VT.is512BitVector())
1472         continue;
1473
1474       if (EltSize >= 32) {
1475         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1476         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1477         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1478         setOperationAction(ISD::VSELECT,             VT, Legal);
1479         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1480         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1481         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1482         setOperationAction(ISD::MLOAD,               VT, Legal);
1483         setOperationAction(ISD::MSTORE,              VT, Legal);
1484       }
1485     }
1486     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1487       MVT VT = (MVT::SimpleValueType)i;
1488
1489       // Do not attempt to promote non-512-bit vectors.
1490       if (!VT.is512BitVector())
1491         continue;
1492
1493       setOperationAction(ISD::SELECT, VT, Promote);
1494       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1495     }
1496   }// has  AVX-512
1497
1498   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1499     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1500     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1501
1502     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1503     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1504
1505     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1506     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1507     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1508     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1509     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1510     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1511     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1512     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1513     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1514     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1515     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1516     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1517     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1518     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1519     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1520     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1521     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1522     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1523     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1524     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1525     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1526     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1527     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1528     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1529     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1530     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1531     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1532     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1533     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1534
1535     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1536     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1537     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1538     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1539     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1540     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1541     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1542     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1543
1544     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1545       const MVT VT = (MVT::SimpleValueType)i;
1546
1547       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1548
1549       // Do not attempt to promote non-512-bit vectors.
1550       if (!VT.is512BitVector())
1551         continue;
1552
1553       if (EltSize < 32) {
1554         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1555         setOperationAction(ISD::VSELECT,             VT, Legal);
1556       }
1557     }
1558   }
1559
1560   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1561     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1562     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1563
1564     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1565     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1566     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1567     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1568     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1569     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1570     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1571     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1572     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1573     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1574
1575     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1576     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1577     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1578     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1579     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1580     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1581     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1582     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1583
1584     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1585     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1586     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1587     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1588     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1589     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1590     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1591     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1592   }
1593
1594   // We want to custom lower some of our intrinsics.
1595   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1596   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1597   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1598   if (!Subtarget->is64Bit())
1599     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1600
1601   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1602   // handle type legalization for these operations here.
1603   //
1604   // FIXME: We really should do custom legalization for addition and
1605   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1606   // than generic legalization for 64-bit multiplication-with-overflow, though.
1607   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1608     // Add/Sub/Mul with overflow operations are custom lowered.
1609     MVT VT = IntVTs[i];
1610     setOperationAction(ISD::SADDO, VT, Custom);
1611     setOperationAction(ISD::UADDO, VT, Custom);
1612     setOperationAction(ISD::SSUBO, VT, Custom);
1613     setOperationAction(ISD::USUBO, VT, Custom);
1614     setOperationAction(ISD::SMULO, VT, Custom);
1615     setOperationAction(ISD::UMULO, VT, Custom);
1616   }
1617
1618
1619   if (!Subtarget->is64Bit()) {
1620     // These libcalls are not available in 32-bit.
1621     setLibcallName(RTLIB::SHL_I128, nullptr);
1622     setLibcallName(RTLIB::SRL_I128, nullptr);
1623     setLibcallName(RTLIB::SRA_I128, nullptr);
1624   }
1625
1626   // Combine sin / cos into one node or libcall if possible.
1627   if (Subtarget->hasSinCos()) {
1628     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1629     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1630     if (Subtarget->isTargetDarwin()) {
1631       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1632       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1633       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1634       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1635     }
1636   }
1637
1638   if (Subtarget->isTargetWin64()) {
1639     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1640     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1641     setOperationAction(ISD::SREM, MVT::i128, Custom);
1642     setOperationAction(ISD::UREM, MVT::i128, Custom);
1643     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1644     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1645   }
1646
1647   // We have target-specific dag combine patterns for the following nodes:
1648   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1649   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1650   setTargetDAGCombine(ISD::BITCAST);
1651   setTargetDAGCombine(ISD::VSELECT);
1652   setTargetDAGCombine(ISD::SELECT);
1653   setTargetDAGCombine(ISD::SHL);
1654   setTargetDAGCombine(ISD::SRA);
1655   setTargetDAGCombine(ISD::SRL);
1656   setTargetDAGCombine(ISD::OR);
1657   setTargetDAGCombine(ISD::AND);
1658   setTargetDAGCombine(ISD::ADD);
1659   setTargetDAGCombine(ISD::FADD);
1660   setTargetDAGCombine(ISD::FSUB);
1661   setTargetDAGCombine(ISD::FMA);
1662   setTargetDAGCombine(ISD::SUB);
1663   setTargetDAGCombine(ISD::LOAD);
1664   setTargetDAGCombine(ISD::MLOAD);
1665   setTargetDAGCombine(ISD::STORE);
1666   setTargetDAGCombine(ISD::MSTORE);
1667   setTargetDAGCombine(ISD::ZERO_EXTEND);
1668   setTargetDAGCombine(ISD::ANY_EXTEND);
1669   setTargetDAGCombine(ISD::SIGN_EXTEND);
1670   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1671   setTargetDAGCombine(ISD::SINT_TO_FP);
1672   setTargetDAGCombine(ISD::UINT_TO_FP);
1673   setTargetDAGCombine(ISD::SETCC);
1674   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1675   setTargetDAGCombine(ISD::BUILD_VECTOR);
1676   setTargetDAGCombine(ISD::MUL);
1677   setTargetDAGCombine(ISD::XOR);
1678
1679   computeRegisterProperties(Subtarget->getRegisterInfo());
1680
1681   // On Darwin, -Os means optimize for size without hurting performance,
1682   // do not reduce the limit.
1683   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1684   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1685   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1686   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1687   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1688   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1689   setPrefLoopAlignment(4); // 2^4 bytes.
1690
1691   // Predictable cmov don't hurt on atom because it's in-order.
1692   PredictableSelectIsExpensive = !Subtarget->isAtom();
1693   EnableExtLdPromotion = true;
1694   setPrefFunctionAlignment(4); // 2^4 bytes.
1695
1696   verifyIntrinsicTables();
1697 }
1698
1699 // This has so far only been implemented for 64-bit MachO.
1700 bool X86TargetLowering::useLoadStackGuardNode() const {
1701   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1702 }
1703
1704 TargetLoweringBase::LegalizeTypeAction
1705 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1706   if (ExperimentalVectorWideningLegalization &&
1707       VT.getVectorNumElements() != 1 &&
1708       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1709     return TypeWidenVector;
1710
1711   return TargetLoweringBase::getPreferredVectorAction(VT);
1712 }
1713
1714 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1715   if (!VT.isVector())
1716     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1717
1718   const unsigned NumElts = VT.getVectorNumElements();
1719   const EVT EltVT = VT.getVectorElementType();
1720   if (VT.is512BitVector()) {
1721     if (Subtarget->hasAVX512())
1722       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1723           EltVT == MVT::f32 || EltVT == MVT::f64)
1724         switch(NumElts) {
1725         case  8: return MVT::v8i1;
1726         case 16: return MVT::v16i1;
1727       }
1728     if (Subtarget->hasBWI())
1729       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1730         switch(NumElts) {
1731         case 32: return MVT::v32i1;
1732         case 64: return MVT::v64i1;
1733       }
1734   }
1735
1736   if (VT.is256BitVector() || VT.is128BitVector()) {
1737     if (Subtarget->hasVLX())
1738       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1739           EltVT == MVT::f32 || EltVT == MVT::f64)
1740         switch(NumElts) {
1741         case 2: return MVT::v2i1;
1742         case 4: return MVT::v4i1;
1743         case 8: return MVT::v8i1;
1744       }
1745     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1746       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1747         switch(NumElts) {
1748         case  8: return MVT::v8i1;
1749         case 16: return MVT::v16i1;
1750         case 32: return MVT::v32i1;
1751       }
1752   }
1753
1754   return VT.changeVectorElementTypeToInteger();
1755 }
1756
1757 /// Helper for getByValTypeAlignment to determine
1758 /// the desired ByVal argument alignment.
1759 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1760   if (MaxAlign == 16)
1761     return;
1762   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1763     if (VTy->getBitWidth() == 128)
1764       MaxAlign = 16;
1765   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1766     unsigned EltAlign = 0;
1767     getMaxByValAlign(ATy->getElementType(), EltAlign);
1768     if (EltAlign > MaxAlign)
1769       MaxAlign = EltAlign;
1770   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1771     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1772       unsigned EltAlign = 0;
1773       getMaxByValAlign(STy->getElementType(i), EltAlign);
1774       if (EltAlign > MaxAlign)
1775         MaxAlign = EltAlign;
1776       if (MaxAlign == 16)
1777         break;
1778     }
1779   }
1780 }
1781
1782 /// Return the desired alignment for ByVal aggregate
1783 /// function arguments in the caller parameter area. For X86, aggregates
1784 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1785 /// are at 4-byte boundaries.
1786 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1787   if (Subtarget->is64Bit()) {
1788     // Max of 8 and alignment of type.
1789     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1790     if (TyAlign > 8)
1791       return TyAlign;
1792     return 8;
1793   }
1794
1795   unsigned Align = 4;
1796   if (Subtarget->hasSSE1())
1797     getMaxByValAlign(Ty, Align);
1798   return Align;
1799 }
1800
1801 /// Returns the target specific optimal type for load
1802 /// and store operations as a result of memset, memcpy, and memmove
1803 /// lowering. If DstAlign is zero that means it's safe to destination
1804 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1805 /// means there isn't a need to check it against alignment requirement,
1806 /// probably because the source does not need to be loaded. If 'IsMemset' is
1807 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1808 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1809 /// source is constant so it does not need to be loaded.
1810 /// It returns EVT::Other if the type should be determined using generic
1811 /// target-independent logic.
1812 EVT
1813 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1814                                        unsigned DstAlign, unsigned SrcAlign,
1815                                        bool IsMemset, bool ZeroMemset,
1816                                        bool MemcpyStrSrc,
1817                                        MachineFunction &MF) const {
1818   const Function *F = MF.getFunction();
1819   if ((!IsMemset || ZeroMemset) &&
1820       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1821     if (Size >= 16 &&
1822         (Subtarget->isUnalignedMemAccessFast() ||
1823          ((DstAlign == 0 || DstAlign >= 16) &&
1824           (SrcAlign == 0 || SrcAlign >= 16)))) {
1825       if (Size >= 32) {
1826         if (Subtarget->hasInt256())
1827           return MVT::v8i32;
1828         if (Subtarget->hasFp256())
1829           return MVT::v8f32;
1830       }
1831       if (Subtarget->hasSSE2())
1832         return MVT::v4i32;
1833       if (Subtarget->hasSSE1())
1834         return MVT::v4f32;
1835     } else if (!MemcpyStrSrc && Size >= 8 &&
1836                !Subtarget->is64Bit() &&
1837                Subtarget->hasSSE2()) {
1838       // Do not use f64 to lower memcpy if source is string constant. It's
1839       // better to use i32 to avoid the loads.
1840       return MVT::f64;
1841     }
1842   }
1843   if (Subtarget->is64Bit() && Size >= 8)
1844     return MVT::i64;
1845   return MVT::i32;
1846 }
1847
1848 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1849   if (VT == MVT::f32)
1850     return X86ScalarSSEf32;
1851   else if (VT == MVT::f64)
1852     return X86ScalarSSEf64;
1853   return true;
1854 }
1855
1856 bool
1857 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1858                                                   unsigned,
1859                                                   unsigned,
1860                                                   bool *Fast) const {
1861   if (Fast)
1862     *Fast = Subtarget->isUnalignedMemAccessFast();
1863   return true;
1864 }
1865
1866 /// Return the entry encoding for a jump table in the
1867 /// current function.  The returned value is a member of the
1868 /// MachineJumpTableInfo::JTEntryKind enum.
1869 unsigned X86TargetLowering::getJumpTableEncoding() const {
1870   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1871   // symbol.
1872   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1873       Subtarget->isPICStyleGOT())
1874     return MachineJumpTableInfo::EK_Custom32;
1875
1876   // Otherwise, use the normal jump table encoding heuristics.
1877   return TargetLowering::getJumpTableEncoding();
1878 }
1879
1880 bool X86TargetLowering::useSoftFloat() const {
1881   return Subtarget->useSoftFloat();
1882 }
1883
1884 const MCExpr *
1885 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1886                                              const MachineBasicBlock *MBB,
1887                                              unsigned uid,MCContext &Ctx) const{
1888   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1889          Subtarget->isPICStyleGOT());
1890   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1891   // entries.
1892   return MCSymbolRefExpr::create(MBB->getSymbol(),
1893                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1894 }
1895
1896 /// Returns relocation base for the given PIC jumptable.
1897 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1898                                                     SelectionDAG &DAG) const {
1899   if (!Subtarget->is64Bit())
1900     // This doesn't have SDLoc associated with it, but is not really the
1901     // same as a Register.
1902     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1903   return Table;
1904 }
1905
1906 /// This returns the relocation base for the given PIC jumptable,
1907 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1908 const MCExpr *X86TargetLowering::
1909 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1910                              MCContext &Ctx) const {
1911   // X86-64 uses RIP relative addressing based on the jump table label.
1912   if (Subtarget->isPICStyleRIPRel())
1913     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1914
1915   // Otherwise, the reference is relative to the PIC base.
1916   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1917 }
1918
1919 std::pair<const TargetRegisterClass *, uint8_t>
1920 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1921                                            MVT VT) const {
1922   const TargetRegisterClass *RRC = nullptr;
1923   uint8_t Cost = 1;
1924   switch (VT.SimpleTy) {
1925   default:
1926     return TargetLowering::findRepresentativeClass(TRI, VT);
1927   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1928     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1929     break;
1930   case MVT::x86mmx:
1931     RRC = &X86::VR64RegClass;
1932     break;
1933   case MVT::f32: case MVT::f64:
1934   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1935   case MVT::v4f32: case MVT::v2f64:
1936   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1937   case MVT::v4f64:
1938     RRC = &X86::VR128RegClass;
1939     break;
1940   }
1941   return std::make_pair(RRC, Cost);
1942 }
1943
1944 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1945                                                unsigned &Offset) const {
1946   if (!Subtarget->isTargetLinux())
1947     return false;
1948
1949   if (Subtarget->is64Bit()) {
1950     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1951     Offset = 0x28;
1952     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1953       AddressSpace = 256;
1954     else
1955       AddressSpace = 257;
1956   } else {
1957     // %gs:0x14 on i386
1958     Offset = 0x14;
1959     AddressSpace = 256;
1960   }
1961   return true;
1962 }
1963
1964 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1965                                             unsigned DestAS) const {
1966   assert(SrcAS != DestAS && "Expected different address spaces!");
1967
1968   return SrcAS < 256 && DestAS < 256;
1969 }
1970
1971 //===----------------------------------------------------------------------===//
1972 //               Return Value Calling Convention Implementation
1973 //===----------------------------------------------------------------------===//
1974
1975 #include "X86GenCallingConv.inc"
1976
1977 bool
1978 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1979                                   MachineFunction &MF, bool isVarArg,
1980                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1981                         LLVMContext &Context) const {
1982   SmallVector<CCValAssign, 16> RVLocs;
1983   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1984   return CCInfo.CheckReturn(Outs, RetCC_X86);
1985 }
1986
1987 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1988   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1989   return ScratchRegs;
1990 }
1991
1992 SDValue
1993 X86TargetLowering::LowerReturn(SDValue Chain,
1994                                CallingConv::ID CallConv, bool isVarArg,
1995                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1996                                const SmallVectorImpl<SDValue> &OutVals,
1997                                SDLoc dl, SelectionDAG &DAG) const {
1998   MachineFunction &MF = DAG.getMachineFunction();
1999   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2000
2001   SmallVector<CCValAssign, 16> RVLocs;
2002   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2003   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2004
2005   SDValue Flag;
2006   SmallVector<SDValue, 6> RetOps;
2007   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2008   // Operand #1 = Bytes To Pop
2009   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2010                    MVT::i16));
2011
2012   // Copy the result values into the output registers.
2013   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2014     CCValAssign &VA = RVLocs[i];
2015     assert(VA.isRegLoc() && "Can only return in registers!");
2016     SDValue ValToCopy = OutVals[i];
2017     EVT ValVT = ValToCopy.getValueType();
2018
2019     // Promote values to the appropriate types.
2020     if (VA.getLocInfo() == CCValAssign::SExt)
2021       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2022     else if (VA.getLocInfo() == CCValAssign::ZExt)
2023       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2024     else if (VA.getLocInfo() == CCValAssign::AExt) {
2025       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2026         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2027       else
2028         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2029     }
2030     else if (VA.getLocInfo() == CCValAssign::BCvt)
2031       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2032
2033     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2034            "Unexpected FP-extend for return value.");
2035
2036     // If this is x86-64, and we disabled SSE, we can't return FP values,
2037     // or SSE or MMX vectors.
2038     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2039          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2040           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2041       report_fatal_error("SSE register return with SSE disabled");
2042     }
2043     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2044     // llvm-gcc has never done it right and no one has noticed, so this
2045     // should be OK for now.
2046     if (ValVT == MVT::f64 &&
2047         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2048       report_fatal_error("SSE2 register return with SSE2 disabled");
2049
2050     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2051     // the RET instruction and handled by the FP Stackifier.
2052     if (VA.getLocReg() == X86::FP0 ||
2053         VA.getLocReg() == X86::FP1) {
2054       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2055       // change the value to the FP stack register class.
2056       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2057         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2058       RetOps.push_back(ValToCopy);
2059       // Don't emit a copytoreg.
2060       continue;
2061     }
2062
2063     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2064     // which is returned in RAX / RDX.
2065     if (Subtarget->is64Bit()) {
2066       if (ValVT == MVT::x86mmx) {
2067         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2068           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2069           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2070                                   ValToCopy);
2071           // If we don't have SSE2 available, convert to v4f32 so the generated
2072           // register is legal.
2073           if (!Subtarget->hasSSE2())
2074             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2075         }
2076       }
2077     }
2078
2079     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2080     Flag = Chain.getValue(1);
2081     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2082   }
2083
2084   // All x86 ABIs require that for returning structs by value we copy
2085   // the sret argument into %rax/%eax (depending on ABI) for the return.
2086   // We saved the argument into a virtual register in the entry block,
2087   // so now we copy the value out and into %rax/%eax.
2088   //
2089   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2090   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2091   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2092   // either case FuncInfo->setSRetReturnReg() will have been called.
2093   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2094     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2095
2096     unsigned RetValReg
2097         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2098           X86::RAX : X86::EAX;
2099     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2100     Flag = Chain.getValue(1);
2101
2102     // RAX/EAX now acts like a return value.
2103     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2104   }
2105
2106   RetOps[0] = Chain;  // Update chain.
2107
2108   // Add the flag if we have it.
2109   if (Flag.getNode())
2110     RetOps.push_back(Flag);
2111
2112   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2113 }
2114
2115 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2116   if (N->getNumValues() != 1)
2117     return false;
2118   if (!N->hasNUsesOfValue(1, 0))
2119     return false;
2120
2121   SDValue TCChain = Chain;
2122   SDNode *Copy = *N->use_begin();
2123   if (Copy->getOpcode() == ISD::CopyToReg) {
2124     // If the copy has a glue operand, we conservatively assume it isn't safe to
2125     // perform a tail call.
2126     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2127       return false;
2128     TCChain = Copy->getOperand(0);
2129   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2130     return false;
2131
2132   bool HasRet = false;
2133   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2134        UI != UE; ++UI) {
2135     if (UI->getOpcode() != X86ISD::RET_FLAG)
2136       return false;
2137     // If we are returning more than one value, we can definitely
2138     // not make a tail call see PR19530
2139     if (UI->getNumOperands() > 4)
2140       return false;
2141     if (UI->getNumOperands() == 4 &&
2142         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2143       return false;
2144     HasRet = true;
2145   }
2146
2147   if (!HasRet)
2148     return false;
2149
2150   Chain = TCChain;
2151   return true;
2152 }
2153
2154 EVT
2155 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2156                                             ISD::NodeType ExtendKind) const {
2157   MVT ReturnMVT;
2158   // TODO: Is this also valid on 32-bit?
2159   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2160     ReturnMVT = MVT::i8;
2161   else
2162     ReturnMVT = MVT::i32;
2163
2164   EVT MinVT = getRegisterType(Context, ReturnMVT);
2165   return VT.bitsLT(MinVT) ? MinVT : VT;
2166 }
2167
2168 /// Lower the result values of a call into the
2169 /// appropriate copies out of appropriate physical registers.
2170 ///
2171 SDValue
2172 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2173                                    CallingConv::ID CallConv, bool isVarArg,
2174                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2175                                    SDLoc dl, SelectionDAG &DAG,
2176                                    SmallVectorImpl<SDValue> &InVals) const {
2177
2178   // Assign locations to each value returned by this call.
2179   SmallVector<CCValAssign, 16> RVLocs;
2180   bool Is64Bit = Subtarget->is64Bit();
2181   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2182                  *DAG.getContext());
2183   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2184
2185   // Copy all of the result registers out of their specified physreg.
2186   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2187     CCValAssign &VA = RVLocs[i];
2188     EVT CopyVT = VA.getLocVT();
2189
2190     // If this is x86-64, and we disabled SSE, we can't return FP values
2191     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2192         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2193       report_fatal_error("SSE register return with SSE disabled");
2194     }
2195
2196     // If we prefer to use the value in xmm registers, copy it out as f80 and
2197     // use a truncate to move it from fp stack reg to xmm reg.
2198     bool RoundAfterCopy = false;
2199     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2200         isScalarFPTypeInSSEReg(VA.getValVT())) {
2201       CopyVT = MVT::f80;
2202       RoundAfterCopy = (CopyVT != VA.getLocVT());
2203     }
2204
2205     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2206                                CopyVT, InFlag).getValue(1);
2207     SDValue Val = Chain.getValue(0);
2208
2209     if (RoundAfterCopy)
2210       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2211                         // This truncation won't change the value.
2212                         DAG.getIntPtrConstant(1, dl));
2213
2214     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2215       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2216
2217     InFlag = Chain.getValue(2);
2218     InVals.push_back(Val);
2219   }
2220
2221   return Chain;
2222 }
2223
2224 //===----------------------------------------------------------------------===//
2225 //                C & StdCall & Fast Calling Convention implementation
2226 //===----------------------------------------------------------------------===//
2227 //  StdCall calling convention seems to be standard for many Windows' API
2228 //  routines and around. It differs from C calling convention just a little:
2229 //  callee should clean up the stack, not caller. Symbols should be also
2230 //  decorated in some fancy way :) It doesn't support any vector arguments.
2231 //  For info on fast calling convention see Fast Calling Convention (tail call)
2232 //  implementation LowerX86_32FastCCCallTo.
2233
2234 /// CallIsStructReturn - Determines whether a call uses struct return
2235 /// semantics.
2236 enum StructReturnType {
2237   NotStructReturn,
2238   RegStructReturn,
2239   StackStructReturn
2240 };
2241 static StructReturnType
2242 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2243   if (Outs.empty())
2244     return NotStructReturn;
2245
2246   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2247   if (!Flags.isSRet())
2248     return NotStructReturn;
2249   if (Flags.isInReg())
2250     return RegStructReturn;
2251   return StackStructReturn;
2252 }
2253
2254 /// Determines whether a function uses struct return semantics.
2255 static StructReturnType
2256 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2257   if (Ins.empty())
2258     return NotStructReturn;
2259
2260   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2261   if (!Flags.isSRet())
2262     return NotStructReturn;
2263   if (Flags.isInReg())
2264     return RegStructReturn;
2265   return StackStructReturn;
2266 }
2267
2268 /// Make a copy of an aggregate at address specified by "Src" to address
2269 /// "Dst" with size and alignment information specified by the specific
2270 /// parameter attribute. The copy will be passed as a byval function parameter.
2271 static SDValue
2272 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2273                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2274                           SDLoc dl) {
2275   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2276
2277   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2278                        /*isVolatile*/false, /*AlwaysInline=*/true,
2279                        /*isTailCall*/false,
2280                        MachinePointerInfo(), MachinePointerInfo());
2281 }
2282
2283 /// Return true if the calling convention is one that
2284 /// supports tail call optimization.
2285 static bool IsTailCallConvention(CallingConv::ID CC) {
2286   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2287           CC == CallingConv::HiPE);
2288 }
2289
2290 /// \brief Return true if the calling convention is a C calling convention.
2291 static bool IsCCallConvention(CallingConv::ID CC) {
2292   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2293           CC == CallingConv::X86_64_SysV);
2294 }
2295
2296 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2297   auto Attr =
2298       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2299   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2300     return false;
2301
2302   CallSite CS(CI);
2303   CallingConv::ID CalleeCC = CS.getCallingConv();
2304   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2305     return false;
2306
2307   return true;
2308 }
2309
2310 /// Return true if the function is being made into
2311 /// a tailcall target by changing its ABI.
2312 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2313                                    bool GuaranteedTailCallOpt) {
2314   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2315 }
2316
2317 SDValue
2318 X86TargetLowering::LowerMemArgument(SDValue Chain,
2319                                     CallingConv::ID CallConv,
2320                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2321                                     SDLoc dl, SelectionDAG &DAG,
2322                                     const CCValAssign &VA,
2323                                     MachineFrameInfo *MFI,
2324                                     unsigned i) const {
2325   // Create the nodes corresponding to a load from this parameter slot.
2326   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2327   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2328       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2329   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2330   EVT ValVT;
2331
2332   // If value is passed by pointer we have address passed instead of the value
2333   // itself.
2334   bool ExtendedInMem = VA.isExtInLoc() &&
2335     VA.getValVT().getScalarType() == MVT::i1;
2336
2337   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2338     ValVT = VA.getLocVT();
2339   else
2340     ValVT = VA.getValVT();
2341
2342   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2343   // changed with more analysis.
2344   // In case of tail call optimization mark all arguments mutable. Since they
2345   // could be overwritten by lowering of arguments in case of a tail call.
2346   if (Flags.isByVal()) {
2347     unsigned Bytes = Flags.getByValSize();
2348     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2349     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2350     return DAG.getFrameIndex(FI, getPointerTy());
2351   } else {
2352     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2353                                     VA.getLocMemOffset(), isImmutable);
2354     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2355     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2356                                MachinePointerInfo::getFixedStack(FI),
2357                                false, false, false, 0);
2358     return ExtendedInMem ?
2359       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2360   }
2361 }
2362
2363 // FIXME: Get this from tablegen.
2364 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2365                                                 const X86Subtarget *Subtarget) {
2366   assert(Subtarget->is64Bit());
2367
2368   if (Subtarget->isCallingConvWin64(CallConv)) {
2369     static const MCPhysReg GPR64ArgRegsWin64[] = {
2370       X86::RCX, X86::RDX, X86::R8,  X86::R9
2371     };
2372     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2373   }
2374
2375   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2376     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2377   };
2378   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2379 }
2380
2381 // FIXME: Get this from tablegen.
2382 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2383                                                 CallingConv::ID CallConv,
2384                                                 const X86Subtarget *Subtarget) {
2385   assert(Subtarget->is64Bit());
2386   if (Subtarget->isCallingConvWin64(CallConv)) {
2387     // The XMM registers which might contain var arg parameters are shadowed
2388     // in their paired GPR.  So we only need to save the GPR to their home
2389     // slots.
2390     // TODO: __vectorcall will change this.
2391     return None;
2392   }
2393
2394   const Function *Fn = MF.getFunction();
2395   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2396   bool isSoftFloat = Subtarget->useSoftFloat();
2397   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2398          "SSE register cannot be used when SSE is disabled!");
2399   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2400     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2401     // registers.
2402     return None;
2403
2404   static const MCPhysReg XMMArgRegs64Bit[] = {
2405     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2406     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2407   };
2408   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2409 }
2410
2411 SDValue
2412 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2413                                         CallingConv::ID CallConv,
2414                                         bool isVarArg,
2415                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2416                                         SDLoc dl,
2417                                         SelectionDAG &DAG,
2418                                         SmallVectorImpl<SDValue> &InVals)
2419                                           const {
2420   MachineFunction &MF = DAG.getMachineFunction();
2421   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2422   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2423
2424   const Function* Fn = MF.getFunction();
2425   if (Fn->hasExternalLinkage() &&
2426       Subtarget->isTargetCygMing() &&
2427       Fn->getName() == "main")
2428     FuncInfo->setForceFramePointer(true);
2429
2430   MachineFrameInfo *MFI = MF.getFrameInfo();
2431   bool Is64Bit = Subtarget->is64Bit();
2432   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2433
2434   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2435          "Var args not supported with calling convention fastcc, ghc or hipe");
2436
2437   // Assign locations to all of the incoming arguments.
2438   SmallVector<CCValAssign, 16> ArgLocs;
2439   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2440
2441   // Allocate shadow area for Win64
2442   if (IsWin64)
2443     CCInfo.AllocateStack(32, 8);
2444
2445   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2446
2447   unsigned LastVal = ~0U;
2448   SDValue ArgValue;
2449   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2450     CCValAssign &VA = ArgLocs[i];
2451     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2452     // places.
2453     assert(VA.getValNo() != LastVal &&
2454            "Don't support value assigned to multiple locs yet");
2455     (void)LastVal;
2456     LastVal = VA.getValNo();
2457
2458     if (VA.isRegLoc()) {
2459       EVT RegVT = VA.getLocVT();
2460       const TargetRegisterClass *RC;
2461       if (RegVT == MVT::i32)
2462         RC = &X86::GR32RegClass;
2463       else if (Is64Bit && RegVT == MVT::i64)
2464         RC = &X86::GR64RegClass;
2465       else if (RegVT == MVT::f32)
2466         RC = &X86::FR32RegClass;
2467       else if (RegVT == MVT::f64)
2468         RC = &X86::FR64RegClass;
2469       else if (RegVT.is512BitVector())
2470         RC = &X86::VR512RegClass;
2471       else if (RegVT.is256BitVector())
2472         RC = &X86::VR256RegClass;
2473       else if (RegVT.is128BitVector())
2474         RC = &X86::VR128RegClass;
2475       else if (RegVT == MVT::x86mmx)
2476         RC = &X86::VR64RegClass;
2477       else if (RegVT == MVT::i1)
2478         RC = &X86::VK1RegClass;
2479       else if (RegVT == MVT::v8i1)
2480         RC = &X86::VK8RegClass;
2481       else if (RegVT == MVT::v16i1)
2482         RC = &X86::VK16RegClass;
2483       else if (RegVT == MVT::v32i1)
2484         RC = &X86::VK32RegClass;
2485       else if (RegVT == MVT::v64i1)
2486         RC = &X86::VK64RegClass;
2487       else
2488         llvm_unreachable("Unknown argument type!");
2489
2490       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2491       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2492
2493       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2494       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2495       // right size.
2496       if (VA.getLocInfo() == CCValAssign::SExt)
2497         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2498                                DAG.getValueType(VA.getValVT()));
2499       else if (VA.getLocInfo() == CCValAssign::ZExt)
2500         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2501                                DAG.getValueType(VA.getValVT()));
2502       else if (VA.getLocInfo() == CCValAssign::BCvt)
2503         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2504
2505       if (VA.isExtInLoc()) {
2506         // Handle MMX values passed in XMM regs.
2507         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2508           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2509         else
2510           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2511       }
2512     } else {
2513       assert(VA.isMemLoc());
2514       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2515     }
2516
2517     // If value is passed via pointer - do a load.
2518     if (VA.getLocInfo() == CCValAssign::Indirect)
2519       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2520                              MachinePointerInfo(), false, false, false, 0);
2521
2522     InVals.push_back(ArgValue);
2523   }
2524
2525   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2526     // All x86 ABIs require that for returning structs by value we copy the
2527     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2528     // the argument into a virtual register so that we can access it from the
2529     // return points.
2530     if (Ins[i].Flags.isSRet()) {
2531       unsigned Reg = FuncInfo->getSRetReturnReg();
2532       if (!Reg) {
2533         MVT PtrTy = getPointerTy();
2534         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2535         FuncInfo->setSRetReturnReg(Reg);
2536       }
2537       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2538       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2539       break;
2540     }
2541   }
2542
2543   unsigned StackSize = CCInfo.getNextStackOffset();
2544   // Align stack specially for tail calls.
2545   if (FuncIsMadeTailCallSafe(CallConv,
2546                              MF.getTarget().Options.GuaranteedTailCallOpt))
2547     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2548
2549   // If the function takes variable number of arguments, make a frame index for
2550   // the start of the first vararg value... for expansion of llvm.va_start. We
2551   // can skip this if there are no va_start calls.
2552   if (MFI->hasVAStart() &&
2553       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2554                    CallConv != CallingConv::X86_ThisCall))) {
2555     FuncInfo->setVarArgsFrameIndex(
2556         MFI->CreateFixedObject(1, StackSize, true));
2557   }
2558
2559   MachineModuleInfo &MMI = MF.getMMI();
2560   const Function *WinEHParent = nullptr;
2561   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2562     WinEHParent = MMI.getWinEHParent(Fn);
2563   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2564   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2565
2566   // Figure out if XMM registers are in use.
2567   assert(!(Subtarget->useSoftFloat() &&
2568            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2569          "SSE register cannot be used when SSE is disabled!");
2570
2571   // 64-bit calling conventions support varargs and register parameters, so we
2572   // have to do extra work to spill them in the prologue.
2573   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2574     // Find the first unallocated argument registers.
2575     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2576     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2577     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2578     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2579     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2580            "SSE register cannot be used when SSE is disabled!");
2581
2582     // Gather all the live in physical registers.
2583     SmallVector<SDValue, 6> LiveGPRs;
2584     SmallVector<SDValue, 8> LiveXMMRegs;
2585     SDValue ALVal;
2586     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2587       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2588       LiveGPRs.push_back(
2589           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2590     }
2591     if (!ArgXMMs.empty()) {
2592       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2593       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2594       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2595         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2596         LiveXMMRegs.push_back(
2597             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2598       }
2599     }
2600
2601     if (IsWin64) {
2602       // Get to the caller-allocated home save location.  Add 8 to account
2603       // for the return address.
2604       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2605       FuncInfo->setRegSaveFrameIndex(
2606           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2607       // Fixup to set vararg frame on shadow area (4 x i64).
2608       if (NumIntRegs < 4)
2609         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2610     } else {
2611       // For X86-64, if there are vararg parameters that are passed via
2612       // registers, then we must store them to their spots on the stack so
2613       // they may be loaded by deferencing the result of va_next.
2614       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2615       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2616       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2617           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2618     }
2619
2620     // Store the integer parameter registers.
2621     SmallVector<SDValue, 8> MemOps;
2622     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2623                                       getPointerTy());
2624     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2625     for (SDValue Val : LiveGPRs) {
2626       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2627                                 DAG.getIntPtrConstant(Offset, dl));
2628       SDValue Store =
2629         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2630                      MachinePointerInfo::getFixedStack(
2631                        FuncInfo->getRegSaveFrameIndex(), Offset),
2632                      false, false, 0);
2633       MemOps.push_back(Store);
2634       Offset += 8;
2635     }
2636
2637     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2638       // Now store the XMM (fp + vector) parameter registers.
2639       SmallVector<SDValue, 12> SaveXMMOps;
2640       SaveXMMOps.push_back(Chain);
2641       SaveXMMOps.push_back(ALVal);
2642       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2643                              FuncInfo->getRegSaveFrameIndex(), dl));
2644       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2645                              FuncInfo->getVarArgsFPOffset(), dl));
2646       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2647                         LiveXMMRegs.end());
2648       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2649                                    MVT::Other, SaveXMMOps));
2650     }
2651
2652     if (!MemOps.empty())
2653       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2654   } else if (IsWinEHOutlined) {
2655     // Get to the caller-allocated home save location.  Add 8 to account
2656     // for the return address.
2657     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2658     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2659         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2660
2661     MMI.getWinEHFuncInfo(Fn)
2662         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2663         FuncInfo->getRegSaveFrameIndex();
2664
2665     // Store the second integer parameter (rdx) into rsp+16 relative to the
2666     // stack pointer at the entry of the function.
2667     SDValue RSFIN =
2668         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2669     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2670     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2671     Chain = DAG.getStore(
2672         Val.getValue(1), dl, Val, RSFIN,
2673         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2674         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2675   }
2676
2677   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2678     // Find the largest legal vector type.
2679     MVT VecVT = MVT::Other;
2680     // FIXME: Only some x86_32 calling conventions support AVX512.
2681     if (Subtarget->hasAVX512() &&
2682         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2683                      CallConv == CallingConv::Intel_OCL_BI)))
2684       VecVT = MVT::v16f32;
2685     else if (Subtarget->hasAVX())
2686       VecVT = MVT::v8f32;
2687     else if (Subtarget->hasSSE2())
2688       VecVT = MVT::v4f32;
2689
2690     // We forward some GPRs and some vector types.
2691     SmallVector<MVT, 2> RegParmTypes;
2692     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2693     RegParmTypes.push_back(IntVT);
2694     if (VecVT != MVT::Other)
2695       RegParmTypes.push_back(VecVT);
2696
2697     // Compute the set of forwarded registers. The rest are scratch.
2698     SmallVectorImpl<ForwardedRegister> &Forwards =
2699         FuncInfo->getForwardedMustTailRegParms();
2700     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2701
2702     // Conservatively forward AL on x86_64, since it might be used for varargs.
2703     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2704       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2705       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2706     }
2707
2708     // Copy all forwards from physical to virtual registers.
2709     for (ForwardedRegister &F : Forwards) {
2710       // FIXME: Can we use a less constrained schedule?
2711       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2712       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2713       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2714     }
2715   }
2716
2717   // Some CCs need callee pop.
2718   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2719                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2720     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2721   } else {
2722     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2723     // If this is an sret function, the return should pop the hidden pointer.
2724     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2725         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2726         argsAreStructReturn(Ins) == StackStructReturn)
2727       FuncInfo->setBytesToPopOnReturn(4);
2728   }
2729
2730   if (!Is64Bit) {
2731     // RegSaveFrameIndex is X86-64 only.
2732     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2733     if (CallConv == CallingConv::X86_FastCall ||
2734         CallConv == CallingConv::X86_ThisCall)
2735       // fastcc functions can't have varargs.
2736       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2737   }
2738
2739   FuncInfo->setArgumentStackSize(StackSize);
2740
2741   if (IsWinEHParent) {
2742     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2743     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2744     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2745     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2746     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2747                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2748                          /*isVolatile=*/true,
2749                          /*isNonTemporal=*/false, /*Alignment=*/0);
2750   }
2751
2752   return Chain;
2753 }
2754
2755 SDValue
2756 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2757                                     SDValue StackPtr, SDValue Arg,
2758                                     SDLoc dl, SelectionDAG &DAG,
2759                                     const CCValAssign &VA,
2760                                     ISD::ArgFlagsTy Flags) const {
2761   unsigned LocMemOffset = VA.getLocMemOffset();
2762   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2763   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2764   if (Flags.isByVal())
2765     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2766
2767   return DAG.getStore(Chain, dl, Arg, PtrOff,
2768                       MachinePointerInfo::getStack(LocMemOffset),
2769                       false, false, 0);
2770 }
2771
2772 /// Emit a load of return address if tail call
2773 /// optimization is performed and it is required.
2774 SDValue
2775 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2776                                            SDValue &OutRetAddr, SDValue Chain,
2777                                            bool IsTailCall, bool Is64Bit,
2778                                            int FPDiff, SDLoc dl) const {
2779   // Adjust the Return address stack slot.
2780   EVT VT = getPointerTy();
2781   OutRetAddr = getReturnAddressFrameIndex(DAG);
2782
2783   // Load the "old" Return address.
2784   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2785                            false, false, false, 0);
2786   return SDValue(OutRetAddr.getNode(), 1);
2787 }
2788
2789 /// Emit a store of the return address if tail call
2790 /// optimization is performed and it is required (FPDiff!=0).
2791 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2792                                         SDValue Chain, SDValue RetAddrFrIdx,
2793                                         EVT PtrVT, unsigned SlotSize,
2794                                         int FPDiff, SDLoc dl) {
2795   // Store the return address to the appropriate stack slot.
2796   if (!FPDiff) return Chain;
2797   // Calculate the new stack slot for the return address.
2798   int NewReturnAddrFI =
2799     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2800                                          false);
2801   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2802   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2803                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2804                        false, false, 0);
2805   return Chain;
2806 }
2807
2808 SDValue
2809 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2810                              SmallVectorImpl<SDValue> &InVals) const {
2811   SelectionDAG &DAG                     = CLI.DAG;
2812   SDLoc &dl                             = CLI.DL;
2813   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2814   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2815   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2816   SDValue Chain                         = CLI.Chain;
2817   SDValue Callee                        = CLI.Callee;
2818   CallingConv::ID CallConv              = CLI.CallConv;
2819   bool &isTailCall                      = CLI.IsTailCall;
2820   bool isVarArg                         = CLI.IsVarArg;
2821
2822   MachineFunction &MF = DAG.getMachineFunction();
2823   bool Is64Bit        = Subtarget->is64Bit();
2824   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2825   StructReturnType SR = callIsStructReturn(Outs);
2826   bool IsSibcall      = false;
2827   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2828   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2829
2830   if (Attr.getValueAsString() == "true")
2831     isTailCall = false;
2832
2833   if (Subtarget->isPICStyleGOT() &&
2834       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2835     // If we are using a GOT, disable tail calls to external symbols with
2836     // default visibility. Tail calling such a symbol requires using a GOT
2837     // relocation, which forces early binding of the symbol. This breaks code
2838     // that require lazy function symbol resolution. Using musttail or
2839     // GuaranteedTailCallOpt will override this.
2840     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2841     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2842                G->getGlobal()->hasDefaultVisibility()))
2843       isTailCall = false;
2844   }
2845
2846   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2847   if (IsMustTail) {
2848     // Force this to be a tail call.  The verifier rules are enough to ensure
2849     // that we can lower this successfully without moving the return address
2850     // around.
2851     isTailCall = true;
2852   } else if (isTailCall) {
2853     // Check if it's really possible to do a tail call.
2854     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2855                     isVarArg, SR != NotStructReturn,
2856                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2857                     Outs, OutVals, Ins, DAG);
2858
2859     // Sibcalls are automatically detected tailcalls which do not require
2860     // ABI changes.
2861     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2862       IsSibcall = true;
2863
2864     if (isTailCall)
2865       ++NumTailCalls;
2866   }
2867
2868   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2869          "Var args not supported with calling convention fastcc, ghc or hipe");
2870
2871   // Analyze operands of the call, assigning locations to each operand.
2872   SmallVector<CCValAssign, 16> ArgLocs;
2873   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2874
2875   // Allocate shadow area for Win64
2876   if (IsWin64)
2877     CCInfo.AllocateStack(32, 8);
2878
2879   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2880
2881   // Get a count of how many bytes are to be pushed on the stack.
2882   unsigned NumBytes = CCInfo.getNextStackOffset();
2883   if (IsSibcall)
2884     // This is a sibcall. The memory operands are available in caller's
2885     // own caller's stack.
2886     NumBytes = 0;
2887   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2888            IsTailCallConvention(CallConv))
2889     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2890
2891   int FPDiff = 0;
2892   if (isTailCall && !IsSibcall && !IsMustTail) {
2893     // Lower arguments at fp - stackoffset + fpdiff.
2894     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2895
2896     FPDiff = NumBytesCallerPushed - NumBytes;
2897
2898     // Set the delta of movement of the returnaddr stackslot.
2899     // But only set if delta is greater than previous delta.
2900     if (FPDiff < X86Info->getTCReturnAddrDelta())
2901       X86Info->setTCReturnAddrDelta(FPDiff);
2902   }
2903
2904   unsigned NumBytesToPush = NumBytes;
2905   unsigned NumBytesToPop = NumBytes;
2906
2907   // If we have an inalloca argument, all stack space has already been allocated
2908   // for us and be right at the top of the stack.  We don't support multiple
2909   // arguments passed in memory when using inalloca.
2910   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2911     NumBytesToPush = 0;
2912     if (!ArgLocs.back().isMemLoc())
2913       report_fatal_error("cannot use inalloca attribute on a register "
2914                          "parameter");
2915     if (ArgLocs.back().getLocMemOffset() != 0)
2916       report_fatal_error("any parameter with the inalloca attribute must be "
2917                          "the only memory argument");
2918   }
2919
2920   if (!IsSibcall)
2921     Chain = DAG.getCALLSEQ_START(
2922         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2923
2924   SDValue RetAddrFrIdx;
2925   // Load return address for tail calls.
2926   if (isTailCall && FPDiff)
2927     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2928                                     Is64Bit, FPDiff, dl);
2929
2930   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2931   SmallVector<SDValue, 8> MemOpChains;
2932   SDValue StackPtr;
2933
2934   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2935   // of tail call optimization arguments are handle later.
2936   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2937   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2938     // Skip inalloca arguments, they have already been written.
2939     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2940     if (Flags.isInAlloca())
2941       continue;
2942
2943     CCValAssign &VA = ArgLocs[i];
2944     EVT RegVT = VA.getLocVT();
2945     SDValue Arg = OutVals[i];
2946     bool isByVal = Flags.isByVal();
2947
2948     // Promote the value if needed.
2949     switch (VA.getLocInfo()) {
2950     default: llvm_unreachable("Unknown loc info!");
2951     case CCValAssign::Full: break;
2952     case CCValAssign::SExt:
2953       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2954       break;
2955     case CCValAssign::ZExt:
2956       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2957       break;
2958     case CCValAssign::AExt:
2959       if (Arg.getValueType().isVector() &&
2960           Arg.getValueType().getScalarType() == MVT::i1)
2961         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2962       else if (RegVT.is128BitVector()) {
2963         // Special case: passing MMX values in XMM registers.
2964         Arg = DAG.getBitcast(MVT::i64, Arg);
2965         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2966         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2967       } else
2968         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2969       break;
2970     case CCValAssign::BCvt:
2971       Arg = DAG.getBitcast(RegVT, Arg);
2972       break;
2973     case CCValAssign::Indirect: {
2974       // Store the argument.
2975       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2976       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2977       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2978                            MachinePointerInfo::getFixedStack(FI),
2979                            false, false, 0);
2980       Arg = SpillSlot;
2981       break;
2982     }
2983     }
2984
2985     if (VA.isRegLoc()) {
2986       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2987       if (isVarArg && IsWin64) {
2988         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2989         // shadow reg if callee is a varargs function.
2990         unsigned ShadowReg = 0;
2991         switch (VA.getLocReg()) {
2992         case X86::XMM0: ShadowReg = X86::RCX; break;
2993         case X86::XMM1: ShadowReg = X86::RDX; break;
2994         case X86::XMM2: ShadowReg = X86::R8; break;
2995         case X86::XMM3: ShadowReg = X86::R9; break;
2996         }
2997         if (ShadowReg)
2998           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2999       }
3000     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3001       assert(VA.isMemLoc());
3002       if (!StackPtr.getNode())
3003         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3004                                       getPointerTy());
3005       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3006                                              dl, DAG, VA, Flags));
3007     }
3008   }
3009
3010   if (!MemOpChains.empty())
3011     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3012
3013   if (Subtarget->isPICStyleGOT()) {
3014     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3015     // GOT pointer.
3016     if (!isTailCall) {
3017       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
3018                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
3019     } else {
3020       // If we are tail calling and generating PIC/GOT style code load the
3021       // address of the callee into ECX. The value in ecx is used as target of
3022       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3023       // for tail calls on PIC/GOT architectures. Normally we would just put the
3024       // address of GOT into ebx and then call target@PLT. But for tail calls
3025       // ebx would be restored (since ebx is callee saved) before jumping to the
3026       // target@PLT.
3027
3028       // Note: The actual moving to ECX is done further down.
3029       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3030       if (G && !G->getGlobal()->hasLocalLinkage() &&
3031           G->getGlobal()->hasDefaultVisibility())
3032         Callee = LowerGlobalAddress(Callee, DAG);
3033       else if (isa<ExternalSymbolSDNode>(Callee))
3034         Callee = LowerExternalSymbol(Callee, DAG);
3035     }
3036   }
3037
3038   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3039     // From AMD64 ABI document:
3040     // For calls that may call functions that use varargs or stdargs
3041     // (prototype-less calls or calls to functions containing ellipsis (...) in
3042     // the declaration) %al is used as hidden argument to specify the number
3043     // of SSE registers used. The contents of %al do not need to match exactly
3044     // the number of registers, but must be an ubound on the number of SSE
3045     // registers used and is in the range 0 - 8 inclusive.
3046
3047     // Count the number of XMM registers allocated.
3048     static const MCPhysReg XMMArgRegs[] = {
3049       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3050       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3051     };
3052     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3053     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3054            && "SSE registers cannot be used when SSE is disabled");
3055
3056     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3057                                         DAG.getConstant(NumXMMRegs, dl,
3058                                                         MVT::i8)));
3059   }
3060
3061   if (isVarArg && IsMustTail) {
3062     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3063     for (const auto &F : Forwards) {
3064       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3065       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3066     }
3067   }
3068
3069   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3070   // don't need this because the eligibility check rejects calls that require
3071   // shuffling arguments passed in memory.
3072   if (!IsSibcall && isTailCall) {
3073     // Force all the incoming stack arguments to be loaded from the stack
3074     // before any new outgoing arguments are stored to the stack, because the
3075     // outgoing stack slots may alias the incoming argument stack slots, and
3076     // the alias isn't otherwise explicit. This is slightly more conservative
3077     // than necessary, because it means that each store effectively depends
3078     // on every argument instead of just those arguments it would clobber.
3079     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3080
3081     SmallVector<SDValue, 8> MemOpChains2;
3082     SDValue FIN;
3083     int FI = 0;
3084     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3085       CCValAssign &VA = ArgLocs[i];
3086       if (VA.isRegLoc())
3087         continue;
3088       assert(VA.isMemLoc());
3089       SDValue Arg = OutVals[i];
3090       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3091       // Skip inalloca arguments.  They don't require any work.
3092       if (Flags.isInAlloca())
3093         continue;
3094       // Create frame index.
3095       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3096       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3097       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3098       FIN = DAG.getFrameIndex(FI, getPointerTy());
3099
3100       if (Flags.isByVal()) {
3101         // Copy relative to framepointer.
3102         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3103         if (!StackPtr.getNode())
3104           StackPtr = DAG.getCopyFromReg(Chain, dl,
3105                                         RegInfo->getStackRegister(),
3106                                         getPointerTy());
3107         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3108
3109         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3110                                                          ArgChain,
3111                                                          Flags, DAG, dl));
3112       } else {
3113         // Store relative to framepointer.
3114         MemOpChains2.push_back(
3115           DAG.getStore(ArgChain, dl, Arg, FIN,
3116                        MachinePointerInfo::getFixedStack(FI),
3117                        false, false, 0));
3118       }
3119     }
3120
3121     if (!MemOpChains2.empty())
3122       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3123
3124     // Store the return address to the appropriate stack slot.
3125     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3126                                      getPointerTy(), RegInfo->getSlotSize(),
3127                                      FPDiff, dl);
3128   }
3129
3130   // Build a sequence of copy-to-reg nodes chained together with token chain
3131   // and flag operands which copy the outgoing args into registers.
3132   SDValue InFlag;
3133   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3134     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3135                              RegsToPass[i].second, InFlag);
3136     InFlag = Chain.getValue(1);
3137   }
3138
3139   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3140     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3141     // In the 64-bit large code model, we have to make all calls
3142     // through a register, since the call instruction's 32-bit
3143     // pc-relative offset may not be large enough to hold the whole
3144     // address.
3145   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3146     // If the callee is a GlobalAddress node (quite common, every direct call
3147     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3148     // it.
3149     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3150
3151     // We should use extra load for direct calls to dllimported functions in
3152     // non-JIT mode.
3153     const GlobalValue *GV = G->getGlobal();
3154     if (!GV->hasDLLImportStorageClass()) {
3155       unsigned char OpFlags = 0;
3156       bool ExtraLoad = false;
3157       unsigned WrapperKind = ISD::DELETED_NODE;
3158
3159       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3160       // external symbols most go through the PLT in PIC mode.  If the symbol
3161       // has hidden or protected visibility, or if it is static or local, then
3162       // we don't need to use the PLT - we can directly call it.
3163       if (Subtarget->isTargetELF() &&
3164           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3165           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3166         OpFlags = X86II::MO_PLT;
3167       } else if (Subtarget->isPICStyleStubAny() &&
3168                  !GV->isStrongDefinitionForLinker() &&
3169                  (!Subtarget->getTargetTriple().isMacOSX() ||
3170                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3171         // PC-relative references to external symbols should go through $stub,
3172         // unless we're building with the leopard linker or later, which
3173         // automatically synthesizes these stubs.
3174         OpFlags = X86II::MO_DARWIN_STUB;
3175       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3176                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3177         // If the function is marked as non-lazy, generate an indirect call
3178         // which loads from the GOT directly. This avoids runtime overhead
3179         // at the cost of eager binding (and one extra byte of encoding).
3180         OpFlags = X86II::MO_GOTPCREL;
3181         WrapperKind = X86ISD::WrapperRIP;
3182         ExtraLoad = true;
3183       }
3184
3185       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3186                                           G->getOffset(), OpFlags);
3187
3188       // Add a wrapper if needed.
3189       if (WrapperKind != ISD::DELETED_NODE)
3190         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3191       // Add extra indirection if needed.
3192       if (ExtraLoad)
3193         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3194                              MachinePointerInfo::getGOT(),
3195                              false, false, false, 0);
3196     }
3197   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3198     unsigned char OpFlags = 0;
3199
3200     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3201     // external symbols should go through the PLT.
3202     if (Subtarget->isTargetELF() &&
3203         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3204       OpFlags = X86II::MO_PLT;
3205     } else if (Subtarget->isPICStyleStubAny() &&
3206                (!Subtarget->getTargetTriple().isMacOSX() ||
3207                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3208       // PC-relative references to external symbols should go through $stub,
3209       // unless we're building with the leopard linker or later, which
3210       // automatically synthesizes these stubs.
3211       OpFlags = X86II::MO_DARWIN_STUB;
3212     }
3213
3214     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3215                                          OpFlags);
3216   } else if (Subtarget->isTarget64BitILP32() &&
3217              Callee->getValueType(0) == MVT::i32) {
3218     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3219     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3220   }
3221
3222   // Returns a chain & a flag for retval copy to use.
3223   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3224   SmallVector<SDValue, 8> Ops;
3225
3226   if (!IsSibcall && isTailCall) {
3227     Chain = DAG.getCALLSEQ_END(Chain,
3228                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3229                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3230     InFlag = Chain.getValue(1);
3231   }
3232
3233   Ops.push_back(Chain);
3234   Ops.push_back(Callee);
3235
3236   if (isTailCall)
3237     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3238
3239   // Add argument registers to the end of the list so that they are known live
3240   // into the call.
3241   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3242     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3243                                   RegsToPass[i].second.getValueType()));
3244
3245   // Add a register mask operand representing the call-preserved registers.
3246   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3247   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3248   assert(Mask && "Missing call preserved mask for calling convention");
3249   Ops.push_back(DAG.getRegisterMask(Mask));
3250
3251   if (InFlag.getNode())
3252     Ops.push_back(InFlag);
3253
3254   if (isTailCall) {
3255     // We used to do:
3256     //// If this is the first return lowered for this function, add the regs
3257     //// to the liveout set for the function.
3258     // This isn't right, although it's probably harmless on x86; liveouts
3259     // should be computed from returns not tail calls.  Consider a void
3260     // function making a tail call to a function returning int.
3261     MF.getFrameInfo()->setHasTailCall();
3262     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3263   }
3264
3265   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3266   InFlag = Chain.getValue(1);
3267
3268   // Create the CALLSEQ_END node.
3269   unsigned NumBytesForCalleeToPop;
3270   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3271                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3272     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3273   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3274            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3275            SR == StackStructReturn)
3276     // If this is a call to a struct-return function, the callee
3277     // pops the hidden struct pointer, so we have to push it back.
3278     // This is common for Darwin/X86, Linux & Mingw32 targets.
3279     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3280     NumBytesForCalleeToPop = 4;
3281   else
3282     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3283
3284   // Returns a flag for retval copy to use.
3285   if (!IsSibcall) {
3286     Chain = DAG.getCALLSEQ_END(Chain,
3287                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3288                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3289                                                      true),
3290                                InFlag, dl);
3291     InFlag = Chain.getValue(1);
3292   }
3293
3294   // Handle result values, copying them out of physregs into vregs that we
3295   // return.
3296   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3297                          Ins, dl, DAG, InVals);
3298 }
3299
3300 //===----------------------------------------------------------------------===//
3301 //                Fast Calling Convention (tail call) implementation
3302 //===----------------------------------------------------------------------===//
3303
3304 //  Like std call, callee cleans arguments, convention except that ECX is
3305 //  reserved for storing the tail called function address. Only 2 registers are
3306 //  free for argument passing (inreg). Tail call optimization is performed
3307 //  provided:
3308 //                * tailcallopt is enabled
3309 //                * caller/callee are fastcc
3310 //  On X86_64 architecture with GOT-style position independent code only local
3311 //  (within module) calls are supported at the moment.
3312 //  To keep the stack aligned according to platform abi the function
3313 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3314 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3315 //  If a tail called function callee has more arguments than the caller the
3316 //  caller needs to make sure that there is room to move the RETADDR to. This is
3317 //  achieved by reserving an area the size of the argument delta right after the
3318 //  original RETADDR, but before the saved framepointer or the spilled registers
3319 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3320 //  stack layout:
3321 //    arg1
3322 //    arg2
3323 //    RETADDR
3324 //    [ new RETADDR
3325 //      move area ]
3326 //    (possible EBP)
3327 //    ESI
3328 //    EDI
3329 //    local1 ..
3330
3331 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3332 /// for a 16 byte align requirement.
3333 unsigned
3334 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3335                                                SelectionDAG& DAG) const {
3336   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3337   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3338   unsigned StackAlignment = TFI.getStackAlignment();
3339   uint64_t AlignMask = StackAlignment - 1;
3340   int64_t Offset = StackSize;
3341   unsigned SlotSize = RegInfo->getSlotSize();
3342   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3343     // Number smaller than 12 so just add the difference.
3344     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3345   } else {
3346     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3347     Offset = ((~AlignMask) & Offset) + StackAlignment +
3348       (StackAlignment-SlotSize);
3349   }
3350   return Offset;
3351 }
3352
3353 /// MatchingStackOffset - Return true if the given stack call argument is
3354 /// already available in the same position (relatively) of the caller's
3355 /// incoming argument stack.
3356 static
3357 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3358                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3359                          const X86InstrInfo *TII) {
3360   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3361   int FI = INT_MAX;
3362   if (Arg.getOpcode() == ISD::CopyFromReg) {
3363     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3364     if (!TargetRegisterInfo::isVirtualRegister(VR))
3365       return false;
3366     MachineInstr *Def = MRI->getVRegDef(VR);
3367     if (!Def)
3368       return false;
3369     if (!Flags.isByVal()) {
3370       if (!TII->isLoadFromStackSlot(Def, FI))
3371         return false;
3372     } else {
3373       unsigned Opcode = Def->getOpcode();
3374       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3375            Opcode == X86::LEA64_32r) &&
3376           Def->getOperand(1).isFI()) {
3377         FI = Def->getOperand(1).getIndex();
3378         Bytes = Flags.getByValSize();
3379       } else
3380         return false;
3381     }
3382   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3383     if (Flags.isByVal())
3384       // ByVal argument is passed in as a pointer but it's now being
3385       // dereferenced. e.g.
3386       // define @foo(%struct.X* %A) {
3387       //   tail call @bar(%struct.X* byval %A)
3388       // }
3389       return false;
3390     SDValue Ptr = Ld->getBasePtr();
3391     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3392     if (!FINode)
3393       return false;
3394     FI = FINode->getIndex();
3395   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3396     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3397     FI = FINode->getIndex();
3398     Bytes = Flags.getByValSize();
3399   } else
3400     return false;
3401
3402   assert(FI != INT_MAX);
3403   if (!MFI->isFixedObjectIndex(FI))
3404     return false;
3405   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3406 }
3407
3408 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3409 /// for tail call optimization. Targets which want to do tail call
3410 /// optimization should implement this function.
3411 bool
3412 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3413                                                      CallingConv::ID CalleeCC,
3414                                                      bool isVarArg,
3415                                                      bool isCalleeStructRet,
3416                                                      bool isCallerStructRet,
3417                                                      Type *RetTy,
3418                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3419                                     const SmallVectorImpl<SDValue> &OutVals,
3420                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3421                                                      SelectionDAG &DAG) const {
3422   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3423     return false;
3424
3425   // If -tailcallopt is specified, make fastcc functions tail-callable.
3426   const MachineFunction &MF = DAG.getMachineFunction();
3427   const Function *CallerF = MF.getFunction();
3428
3429   // If the function return type is x86_fp80 and the callee return type is not,
3430   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3431   // perform a tailcall optimization here.
3432   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3433     return false;
3434
3435   CallingConv::ID CallerCC = CallerF->getCallingConv();
3436   bool CCMatch = CallerCC == CalleeCC;
3437   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3438   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3439
3440   // Win64 functions have extra shadow space for argument homing. Don't do the
3441   // sibcall if the caller and callee have mismatched expectations for this
3442   // space.
3443   if (IsCalleeWin64 != IsCallerWin64)
3444     return false;
3445
3446   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3447     if (IsTailCallConvention(CalleeCC) && CCMatch)
3448       return true;
3449     return false;
3450   }
3451
3452   // Look for obvious safe cases to perform tail call optimization that do not
3453   // require ABI changes. This is what gcc calls sibcall.
3454
3455   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3456   // emit a special epilogue.
3457   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3458   if (RegInfo->needsStackRealignment(MF))
3459     return false;
3460
3461   // Also avoid sibcall optimization if either caller or callee uses struct
3462   // return semantics.
3463   if (isCalleeStructRet || isCallerStructRet)
3464     return false;
3465
3466   // An stdcall/thiscall caller is expected to clean up its arguments; the
3467   // callee isn't going to do that.
3468   // FIXME: this is more restrictive than needed. We could produce a tailcall
3469   // when the stack adjustment matches. For example, with a thiscall that takes
3470   // only one argument.
3471   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3472                    CallerCC == CallingConv::X86_ThisCall))
3473     return false;
3474
3475   // Do not sibcall optimize vararg calls unless all arguments are passed via
3476   // registers.
3477   if (isVarArg && !Outs.empty()) {
3478
3479     // Optimizing for varargs on Win64 is unlikely to be safe without
3480     // additional testing.
3481     if (IsCalleeWin64 || IsCallerWin64)
3482       return false;
3483
3484     SmallVector<CCValAssign, 16> ArgLocs;
3485     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3486                    *DAG.getContext());
3487
3488     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3489     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3490       if (!ArgLocs[i].isRegLoc())
3491         return false;
3492   }
3493
3494   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3495   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3496   // this into a sibcall.
3497   bool Unused = false;
3498   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3499     if (!Ins[i].Used) {
3500       Unused = true;
3501       break;
3502     }
3503   }
3504   if (Unused) {
3505     SmallVector<CCValAssign, 16> RVLocs;
3506     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3507                    *DAG.getContext());
3508     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3509     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3510       CCValAssign &VA = RVLocs[i];
3511       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3512         return false;
3513     }
3514   }
3515
3516   // If the calling conventions do not match, then we'd better make sure the
3517   // results are returned in the same way as what the caller expects.
3518   if (!CCMatch) {
3519     SmallVector<CCValAssign, 16> RVLocs1;
3520     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3521                     *DAG.getContext());
3522     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3523
3524     SmallVector<CCValAssign, 16> RVLocs2;
3525     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3526                     *DAG.getContext());
3527     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3528
3529     if (RVLocs1.size() != RVLocs2.size())
3530       return false;
3531     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3532       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3533         return false;
3534       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3535         return false;
3536       if (RVLocs1[i].isRegLoc()) {
3537         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3538           return false;
3539       } else {
3540         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3541           return false;
3542       }
3543     }
3544   }
3545
3546   // If the callee takes no arguments then go on to check the results of the
3547   // call.
3548   if (!Outs.empty()) {
3549     // Check if stack adjustment is needed. For now, do not do this if any
3550     // argument is passed on the stack.
3551     SmallVector<CCValAssign, 16> ArgLocs;
3552     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3553                    *DAG.getContext());
3554
3555     // Allocate shadow area for Win64
3556     if (IsCalleeWin64)
3557       CCInfo.AllocateStack(32, 8);
3558
3559     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3560     if (CCInfo.getNextStackOffset()) {
3561       MachineFunction &MF = DAG.getMachineFunction();
3562       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3563         return false;
3564
3565       // Check if the arguments are already laid out in the right way as
3566       // the caller's fixed stack objects.
3567       MachineFrameInfo *MFI = MF.getFrameInfo();
3568       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3569       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3570       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3571         CCValAssign &VA = ArgLocs[i];
3572         SDValue Arg = OutVals[i];
3573         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3574         if (VA.getLocInfo() == CCValAssign::Indirect)
3575           return false;
3576         if (!VA.isRegLoc()) {
3577           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3578                                    MFI, MRI, TII))
3579             return false;
3580         }
3581       }
3582     }
3583
3584     // If the tailcall address may be in a register, then make sure it's
3585     // possible to register allocate for it. In 32-bit, the call address can
3586     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3587     // callee-saved registers are restored. These happen to be the same
3588     // registers used to pass 'inreg' arguments so watch out for those.
3589     if (!Subtarget->is64Bit() &&
3590         ((!isa<GlobalAddressSDNode>(Callee) &&
3591           !isa<ExternalSymbolSDNode>(Callee)) ||
3592          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3593       unsigned NumInRegs = 0;
3594       // In PIC we need an extra register to formulate the address computation
3595       // for the callee.
3596       unsigned MaxInRegs =
3597         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3598
3599       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3600         CCValAssign &VA = ArgLocs[i];
3601         if (!VA.isRegLoc())
3602           continue;
3603         unsigned Reg = VA.getLocReg();
3604         switch (Reg) {
3605         default: break;
3606         case X86::EAX: case X86::EDX: case X86::ECX:
3607           if (++NumInRegs == MaxInRegs)
3608             return false;
3609           break;
3610         }
3611       }
3612     }
3613   }
3614
3615   return true;
3616 }
3617
3618 FastISel *
3619 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3620                                   const TargetLibraryInfo *libInfo) const {
3621   return X86::createFastISel(funcInfo, libInfo);
3622 }
3623
3624 //===----------------------------------------------------------------------===//
3625 //                           Other Lowering Hooks
3626 //===----------------------------------------------------------------------===//
3627
3628 static bool MayFoldLoad(SDValue Op) {
3629   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3630 }
3631
3632 static bool MayFoldIntoStore(SDValue Op) {
3633   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3634 }
3635
3636 static bool isTargetShuffle(unsigned Opcode) {
3637   switch(Opcode) {
3638   default: return false;
3639   case X86ISD::BLENDI:
3640   case X86ISD::PSHUFB:
3641   case X86ISD::PSHUFD:
3642   case X86ISD::PSHUFHW:
3643   case X86ISD::PSHUFLW:
3644   case X86ISD::SHUFP:
3645   case X86ISD::PALIGNR:
3646   case X86ISD::MOVLHPS:
3647   case X86ISD::MOVLHPD:
3648   case X86ISD::MOVHLPS:
3649   case X86ISD::MOVLPS:
3650   case X86ISD::MOVLPD:
3651   case X86ISD::MOVSHDUP:
3652   case X86ISD::MOVSLDUP:
3653   case X86ISD::MOVDDUP:
3654   case X86ISD::MOVSS:
3655   case X86ISD::MOVSD:
3656   case X86ISD::UNPCKL:
3657   case X86ISD::UNPCKH:
3658   case X86ISD::VPERMILPI:
3659   case X86ISD::VPERM2X128:
3660   case X86ISD::VPERMI:
3661     return true;
3662   }
3663 }
3664
3665 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3666                                     SDValue V1, unsigned TargetMask,
3667                                     SelectionDAG &DAG) {
3668   switch(Opc) {
3669   default: llvm_unreachable("Unknown x86 shuffle node");
3670   case X86ISD::PSHUFD:
3671   case X86ISD::PSHUFHW:
3672   case X86ISD::PSHUFLW:
3673   case X86ISD::VPERMILPI:
3674   case X86ISD::VPERMI:
3675     return DAG.getNode(Opc, dl, VT, V1,
3676                        DAG.getConstant(TargetMask, dl, MVT::i8));
3677   }
3678 }
3679
3680 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3681                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3682   switch(Opc) {
3683   default: llvm_unreachable("Unknown x86 shuffle node");
3684   case X86ISD::MOVLHPS:
3685   case X86ISD::MOVLHPD:
3686   case X86ISD::MOVHLPS:
3687   case X86ISD::MOVLPS:
3688   case X86ISD::MOVLPD:
3689   case X86ISD::MOVSS:
3690   case X86ISD::MOVSD:
3691   case X86ISD::UNPCKL:
3692   case X86ISD::UNPCKH:
3693     return DAG.getNode(Opc, dl, VT, V1, V2);
3694   }
3695 }
3696
3697 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3698   MachineFunction &MF = DAG.getMachineFunction();
3699   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3700   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3701   int ReturnAddrIndex = FuncInfo->getRAIndex();
3702
3703   if (ReturnAddrIndex == 0) {
3704     // Set up a frame object for the return address.
3705     unsigned SlotSize = RegInfo->getSlotSize();
3706     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3707                                                            -(int64_t)SlotSize,
3708                                                            false);
3709     FuncInfo->setRAIndex(ReturnAddrIndex);
3710   }
3711
3712   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3713 }
3714
3715 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3716                                        bool hasSymbolicDisplacement) {
3717   // Offset should fit into 32 bit immediate field.
3718   if (!isInt<32>(Offset))
3719     return false;
3720
3721   // If we don't have a symbolic displacement - we don't have any extra
3722   // restrictions.
3723   if (!hasSymbolicDisplacement)
3724     return true;
3725
3726   // FIXME: Some tweaks might be needed for medium code model.
3727   if (M != CodeModel::Small && M != CodeModel::Kernel)
3728     return false;
3729
3730   // For small code model we assume that latest object is 16MB before end of 31
3731   // bits boundary. We may also accept pretty large negative constants knowing
3732   // that all objects are in the positive half of address space.
3733   if (M == CodeModel::Small && Offset < 16*1024*1024)
3734     return true;
3735
3736   // For kernel code model we know that all object resist in the negative half
3737   // of 32bits address space. We may not accept negative offsets, since they may
3738   // be just off and we may accept pretty large positive ones.
3739   if (M == CodeModel::Kernel && Offset >= 0)
3740     return true;
3741
3742   return false;
3743 }
3744
3745 /// isCalleePop - Determines whether the callee is required to pop its
3746 /// own arguments. Callee pop is necessary to support tail calls.
3747 bool X86::isCalleePop(CallingConv::ID CallingConv,
3748                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3749   switch (CallingConv) {
3750   default:
3751     return false;
3752   case CallingConv::X86_StdCall:
3753   case CallingConv::X86_FastCall:
3754   case CallingConv::X86_ThisCall:
3755     return !is64Bit;
3756   case CallingConv::Fast:
3757   case CallingConv::GHC:
3758   case CallingConv::HiPE:
3759     if (IsVarArg)
3760       return false;
3761     return TailCallOpt;
3762   }
3763 }
3764
3765 /// \brief Return true if the condition is an unsigned comparison operation.
3766 static bool isX86CCUnsigned(unsigned X86CC) {
3767   switch (X86CC) {
3768   default: llvm_unreachable("Invalid integer condition!");
3769   case X86::COND_E:     return true;
3770   case X86::COND_G:     return false;
3771   case X86::COND_GE:    return false;
3772   case X86::COND_L:     return false;
3773   case X86::COND_LE:    return false;
3774   case X86::COND_NE:    return true;
3775   case X86::COND_B:     return true;
3776   case X86::COND_A:     return true;
3777   case X86::COND_BE:    return true;
3778   case X86::COND_AE:    return true;
3779   }
3780   llvm_unreachable("covered switch fell through?!");
3781 }
3782
3783 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3784 /// specific condition code, returning the condition code and the LHS/RHS of the
3785 /// comparison to make.
3786 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3787                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3788   if (!isFP) {
3789     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3790       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3791         // X > -1   -> X == 0, jump !sign.
3792         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3793         return X86::COND_NS;
3794       }
3795       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3796         // X < 0   -> X == 0, jump on sign.
3797         return X86::COND_S;
3798       }
3799       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3800         // X < 1   -> X <= 0
3801         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3802         return X86::COND_LE;
3803       }
3804     }
3805
3806     switch (SetCCOpcode) {
3807     default: llvm_unreachable("Invalid integer condition!");
3808     case ISD::SETEQ:  return X86::COND_E;
3809     case ISD::SETGT:  return X86::COND_G;
3810     case ISD::SETGE:  return X86::COND_GE;
3811     case ISD::SETLT:  return X86::COND_L;
3812     case ISD::SETLE:  return X86::COND_LE;
3813     case ISD::SETNE:  return X86::COND_NE;
3814     case ISD::SETULT: return X86::COND_B;
3815     case ISD::SETUGT: return X86::COND_A;
3816     case ISD::SETULE: return X86::COND_BE;
3817     case ISD::SETUGE: return X86::COND_AE;
3818     }
3819   }
3820
3821   // First determine if it is required or is profitable to flip the operands.
3822
3823   // If LHS is a foldable load, but RHS is not, flip the condition.
3824   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3825       !ISD::isNON_EXTLoad(RHS.getNode())) {
3826     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3827     std::swap(LHS, RHS);
3828   }
3829
3830   switch (SetCCOpcode) {
3831   default: break;
3832   case ISD::SETOLT:
3833   case ISD::SETOLE:
3834   case ISD::SETUGT:
3835   case ISD::SETUGE:
3836     std::swap(LHS, RHS);
3837     break;
3838   }
3839
3840   // On a floating point condition, the flags are set as follows:
3841   // ZF  PF  CF   op
3842   //  0 | 0 | 0 | X > Y
3843   //  0 | 0 | 1 | X < Y
3844   //  1 | 0 | 0 | X == Y
3845   //  1 | 1 | 1 | unordered
3846   switch (SetCCOpcode) {
3847   default: llvm_unreachable("Condcode should be pre-legalized away");
3848   case ISD::SETUEQ:
3849   case ISD::SETEQ:   return X86::COND_E;
3850   case ISD::SETOLT:              // flipped
3851   case ISD::SETOGT:
3852   case ISD::SETGT:   return X86::COND_A;
3853   case ISD::SETOLE:              // flipped
3854   case ISD::SETOGE:
3855   case ISD::SETGE:   return X86::COND_AE;
3856   case ISD::SETUGT:              // flipped
3857   case ISD::SETULT:
3858   case ISD::SETLT:   return X86::COND_B;
3859   case ISD::SETUGE:              // flipped
3860   case ISD::SETULE:
3861   case ISD::SETLE:   return X86::COND_BE;
3862   case ISD::SETONE:
3863   case ISD::SETNE:   return X86::COND_NE;
3864   case ISD::SETUO:   return X86::COND_P;
3865   case ISD::SETO:    return X86::COND_NP;
3866   case ISD::SETOEQ:
3867   case ISD::SETUNE:  return X86::COND_INVALID;
3868   }
3869 }
3870
3871 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3872 /// code. Current x86 isa includes the following FP cmov instructions:
3873 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3874 static bool hasFPCMov(unsigned X86CC) {
3875   switch (X86CC) {
3876   default:
3877     return false;
3878   case X86::COND_B:
3879   case X86::COND_BE:
3880   case X86::COND_E:
3881   case X86::COND_P:
3882   case X86::COND_A:
3883   case X86::COND_AE:
3884   case X86::COND_NE:
3885   case X86::COND_NP:
3886     return true;
3887   }
3888 }
3889
3890 /// isFPImmLegal - Returns true if the target can instruction select the
3891 /// specified FP immediate natively. If false, the legalizer will
3892 /// materialize the FP immediate as a load from a constant pool.
3893 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3894   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3895     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3896       return true;
3897   }
3898   return false;
3899 }
3900
3901 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3902                                               ISD::LoadExtType ExtTy,
3903                                               EVT NewVT) const {
3904   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3905   // relocation target a movq or addq instruction: don't let the load shrink.
3906   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3907   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3908     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3909       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3910   return true;
3911 }
3912
3913 /// \brief Returns true if it is beneficial to convert a load of a constant
3914 /// to just the constant itself.
3915 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3916                                                           Type *Ty) const {
3917   assert(Ty->isIntegerTy());
3918
3919   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3920   if (BitSize == 0 || BitSize > 64)
3921     return false;
3922   return true;
3923 }
3924
3925 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3926                                                 unsigned Index) const {
3927   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3928     return false;
3929
3930   return (Index == 0 || Index == ResVT.getVectorNumElements());
3931 }
3932
3933 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3934   // Speculate cttz only if we can directly use TZCNT.
3935   return Subtarget->hasBMI();
3936 }
3937
3938 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3939   // Speculate ctlz only if we can directly use LZCNT.
3940   return Subtarget->hasLZCNT();
3941 }
3942
3943 /// isUndefInRange - Return true if every element in Mask, beginning
3944 /// from position Pos and ending in Pos+Size is undef.
3945 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3946   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
3947     if (0 <= Mask[i])
3948       return false;
3949   return true;
3950 }
3951
3952 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3953 /// the specified range (L, H].
3954 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3955   return (Val < 0) || (Val >= Low && Val < Hi);
3956 }
3957
3958 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3959 /// specified value.
3960 static bool isUndefOrEqual(int Val, int CmpVal) {
3961   return (Val < 0 || Val == CmpVal);
3962 }
3963
3964 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3965 /// from position Pos and ending in Pos+Size, falls within the specified
3966 /// sequential range (Low, Low+Size]. or is undef.
3967 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3968                                        unsigned Pos, unsigned Size, int Low) {
3969   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3970     if (!isUndefOrEqual(Mask[i], Low))
3971       return false;
3972   return true;
3973 }
3974
3975 /// isVEXTRACTIndex - Return true if the specified
3976 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3977 /// suitable for instruction that extract 128 or 256 bit vectors
3978 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3979   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3980   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3981     return false;
3982
3983   // The index should be aligned on a vecWidth-bit boundary.
3984   uint64_t Index =
3985     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3986
3987   MVT VT = N->getSimpleValueType(0);
3988   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3989   bool Result = (Index * ElSize) % vecWidth == 0;
3990
3991   return Result;
3992 }
3993
3994 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3995 /// operand specifies a subvector insert that is suitable for input to
3996 /// insertion of 128 or 256-bit subvectors
3997 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3998   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3999   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4000     return false;
4001   // The index should be aligned on a vecWidth-bit boundary.
4002   uint64_t Index =
4003     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4004
4005   MVT VT = N->getSimpleValueType(0);
4006   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4007   bool Result = (Index * ElSize) % vecWidth == 0;
4008
4009   return Result;
4010 }
4011
4012 bool X86::isVINSERT128Index(SDNode *N) {
4013   return isVINSERTIndex(N, 128);
4014 }
4015
4016 bool X86::isVINSERT256Index(SDNode *N) {
4017   return isVINSERTIndex(N, 256);
4018 }
4019
4020 bool X86::isVEXTRACT128Index(SDNode *N) {
4021   return isVEXTRACTIndex(N, 128);
4022 }
4023
4024 bool X86::isVEXTRACT256Index(SDNode *N) {
4025   return isVEXTRACTIndex(N, 256);
4026 }
4027
4028 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4029   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4030   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4031     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4032
4033   uint64_t Index =
4034     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4035
4036   MVT VecVT = N->getOperand(0).getSimpleValueType();
4037   MVT ElVT = VecVT.getVectorElementType();
4038
4039   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4040   return Index / NumElemsPerChunk;
4041 }
4042
4043 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4044   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4045   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4046     llvm_unreachable("Illegal insert subvector for VINSERT");
4047
4048   uint64_t Index =
4049     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4050
4051   MVT VecVT = N->getSimpleValueType(0);
4052   MVT ElVT = VecVT.getVectorElementType();
4053
4054   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4055   return Index / NumElemsPerChunk;
4056 }
4057
4058 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4059 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4060 /// and VINSERTI128 instructions.
4061 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4062   return getExtractVEXTRACTImmediate(N, 128);
4063 }
4064
4065 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4066 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4067 /// and VINSERTI64x4 instructions.
4068 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4069   return getExtractVEXTRACTImmediate(N, 256);
4070 }
4071
4072 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4073 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4074 /// and VINSERTI128 instructions.
4075 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4076   return getInsertVINSERTImmediate(N, 128);
4077 }
4078
4079 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4080 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4081 /// and VINSERTI64x4 instructions.
4082 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4083   return getInsertVINSERTImmediate(N, 256);
4084 }
4085
4086 /// isZero - Returns true if Elt is a constant integer zero
4087 static bool isZero(SDValue V) {
4088   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4089   return C && C->isNullValue();
4090 }
4091
4092 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4093 /// constant +0.0.
4094 bool X86::isZeroNode(SDValue Elt) {
4095   if (isZero(Elt))
4096     return true;
4097   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4098     return CFP->getValueAPF().isPosZero();
4099   return false;
4100 }
4101
4102 /// getZeroVector - Returns a vector of specified type with all zero elements.
4103 ///
4104 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4105                              SelectionDAG &DAG, SDLoc dl) {
4106   assert(VT.isVector() && "Expected a vector type");
4107
4108   // Always build SSE zero vectors as <4 x i32> bitcasted
4109   // to their dest type. This ensures they get CSE'd.
4110   SDValue Vec;
4111   if (VT.is128BitVector()) {  // SSE
4112     if (Subtarget->hasSSE2()) {  // SSE2
4113       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4114       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4115     } else { // SSE1
4116       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4117       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4118     }
4119   } else if (VT.is256BitVector()) { // AVX
4120     if (Subtarget->hasInt256()) { // AVX2
4121       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4122       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4123       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4124     } else {
4125       // 256-bit logic and arithmetic instructions in AVX are all
4126       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4127       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4128       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4129       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4130     }
4131   } else if (VT.is512BitVector()) { // AVX-512
4132       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4133       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4134                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4135       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4136   } else if (VT.getScalarType() == MVT::i1) {
4137
4138     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4139             && "Unexpected vector type");
4140     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4141             && "Unexpected vector type");
4142     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4143     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4144     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4145   } else
4146     llvm_unreachable("Unexpected vector type");
4147
4148   return DAG.getBitcast(VT, Vec);
4149 }
4150
4151 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4152                                 SelectionDAG &DAG, SDLoc dl,
4153                                 unsigned vectorWidth) {
4154   assert((vectorWidth == 128 || vectorWidth == 256) &&
4155          "Unsupported vector width");
4156   EVT VT = Vec.getValueType();
4157   EVT ElVT = VT.getVectorElementType();
4158   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4159   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4160                                   VT.getVectorNumElements()/Factor);
4161
4162   // Extract from UNDEF is UNDEF.
4163   if (Vec.getOpcode() == ISD::UNDEF)
4164     return DAG.getUNDEF(ResultVT);
4165
4166   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4167   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4168
4169   // This is the index of the first element of the vectorWidth-bit chunk
4170   // we want.
4171   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4172                                * ElemsPerChunk);
4173
4174   // If the input is a buildvector just emit a smaller one.
4175   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4176     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4177                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4178                                     ElemsPerChunk));
4179
4180   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4181   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4182 }
4183
4184 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4185 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4186 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4187 /// instructions or a simple subregister reference. Idx is an index in the
4188 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4189 /// lowering EXTRACT_VECTOR_ELT operations easier.
4190 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4191                                    SelectionDAG &DAG, SDLoc dl) {
4192   assert((Vec.getValueType().is256BitVector() ||
4193           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4194   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4195 }
4196
4197 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4198 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4199                                    SelectionDAG &DAG, SDLoc dl) {
4200   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4201   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4202 }
4203
4204 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4205                                unsigned IdxVal, SelectionDAG &DAG,
4206                                SDLoc dl, unsigned vectorWidth) {
4207   assert((vectorWidth == 128 || vectorWidth == 256) &&
4208          "Unsupported vector width");
4209   // Inserting UNDEF is Result
4210   if (Vec.getOpcode() == ISD::UNDEF)
4211     return Result;
4212   EVT VT = Vec.getValueType();
4213   EVT ElVT = VT.getVectorElementType();
4214   EVT ResultVT = Result.getValueType();
4215
4216   // Insert the relevant vectorWidth bits.
4217   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4218
4219   // This is the index of the first element of the vectorWidth-bit chunk
4220   // we want.
4221   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4222                                * ElemsPerChunk);
4223
4224   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4225   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4226 }
4227
4228 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4229 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4230 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4231 /// simple superregister reference.  Idx is an index in the 128 bits
4232 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4233 /// lowering INSERT_VECTOR_ELT operations easier.
4234 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4235                                   SelectionDAG &DAG, SDLoc dl) {
4236   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4237
4238   // For insertion into the zero index (low half) of a 256-bit vector, it is
4239   // more efficient to generate a blend with immediate instead of an insert*128.
4240   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4241   // extend the subvector to the size of the result vector. Make sure that
4242   // we are not recursing on that node by checking for undef here.
4243   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4244       Result.getOpcode() != ISD::UNDEF) {
4245     EVT ResultVT = Result.getValueType();
4246     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4247     SDValue Undef = DAG.getUNDEF(ResultVT);
4248     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4249                                  Vec, ZeroIndex);
4250
4251     // The blend instruction, and therefore its mask, depend on the data type.
4252     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4253     if (ScalarType.isFloatingPoint()) {
4254       // Choose either vblendps (float) or vblendpd (double).
4255       unsigned ScalarSize = ScalarType.getSizeInBits();
4256       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4257       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4258       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4259       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4260     }
4261
4262     const X86Subtarget &Subtarget =
4263     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4264
4265     // AVX2 is needed for 256-bit integer blend support.
4266     // Integers must be cast to 32-bit because there is only vpblendd;
4267     // vpblendw can't be used for this because it has a handicapped mask.
4268
4269     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4270     // is still more efficient than using the wrong domain vinsertf128 that
4271     // will be created by InsertSubVector().
4272     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4273
4274     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4275     Vec256 = DAG.getBitcast(CastVT, Vec256);
4276     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4277     return DAG.getBitcast(ResultVT, Vec256);
4278   }
4279
4280   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4281 }
4282
4283 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4284                                   SelectionDAG &DAG, SDLoc dl) {
4285   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4286   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4287 }
4288
4289 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4290 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4291 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4292 /// large BUILD_VECTORS.
4293 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4294                                    unsigned NumElems, SelectionDAG &DAG,
4295                                    SDLoc dl) {
4296   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4297   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4298 }
4299
4300 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4301                                    unsigned NumElems, SelectionDAG &DAG,
4302                                    SDLoc dl) {
4303   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4304   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4305 }
4306
4307 /// getOnesVector - Returns a vector of specified type with all bits set.
4308 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4309 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4310 /// Then bitcast to their original type, ensuring they get CSE'd.
4311 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4312                              SDLoc dl) {
4313   assert(VT.isVector() && "Expected a vector type");
4314
4315   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4316   SDValue Vec;
4317   if (VT.is256BitVector()) {
4318     if (HasInt256) { // AVX2
4319       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4320       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4321     } else { // AVX
4322       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4323       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4324     }
4325   } else if (VT.is128BitVector()) {
4326     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4327   } else
4328     llvm_unreachable("Unexpected vector type");
4329
4330   return DAG.getBitcast(VT, Vec);
4331 }
4332
4333 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4334 /// operation of specified width.
4335 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4336                        SDValue V2) {
4337   unsigned NumElems = VT.getVectorNumElements();
4338   SmallVector<int, 8> Mask;
4339   Mask.push_back(NumElems);
4340   for (unsigned i = 1; i != NumElems; ++i)
4341     Mask.push_back(i);
4342   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4343 }
4344
4345 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4346 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4347                           SDValue V2) {
4348   unsigned NumElems = VT.getVectorNumElements();
4349   SmallVector<int, 8> Mask;
4350   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4351     Mask.push_back(i);
4352     Mask.push_back(i + NumElems);
4353   }
4354   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4355 }
4356
4357 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4358 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4359                           SDValue V2) {
4360   unsigned NumElems = VT.getVectorNumElements();
4361   SmallVector<int, 8> Mask;
4362   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4363     Mask.push_back(i + Half);
4364     Mask.push_back(i + NumElems + Half);
4365   }
4366   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4367 }
4368
4369 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4370 /// vector of zero or undef vector.  This produces a shuffle where the low
4371 /// element of V2 is swizzled into the zero/undef vector, landing at element
4372 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4373 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4374                                            bool IsZero,
4375                                            const X86Subtarget *Subtarget,
4376                                            SelectionDAG &DAG) {
4377   MVT VT = V2.getSimpleValueType();
4378   SDValue V1 = IsZero
4379     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4380   unsigned NumElems = VT.getVectorNumElements();
4381   SmallVector<int, 16> MaskVec;
4382   for (unsigned i = 0; i != NumElems; ++i)
4383     // If this is the insertion idx, put the low elt of V2 here.
4384     MaskVec.push_back(i == Idx ? NumElems : i);
4385   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4386 }
4387
4388 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4389 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4390 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4391 /// shuffles which use a single input multiple times, and in those cases it will
4392 /// adjust the mask to only have indices within that single input.
4393 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4394 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4395                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4396   unsigned NumElems = VT.getVectorNumElements();
4397   SDValue ImmN;
4398
4399   IsUnary = false;
4400   bool IsFakeUnary = false;
4401   switch(N->getOpcode()) {
4402   case X86ISD::BLENDI:
4403     ImmN = N->getOperand(N->getNumOperands()-1);
4404     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4405     break;
4406   case X86ISD::SHUFP:
4407     ImmN = N->getOperand(N->getNumOperands()-1);
4408     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4409     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4410     break;
4411   case X86ISD::UNPCKH:
4412     DecodeUNPCKHMask(VT, Mask);
4413     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4414     break;
4415   case X86ISD::UNPCKL:
4416     DecodeUNPCKLMask(VT, Mask);
4417     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4418     break;
4419   case X86ISD::MOVHLPS:
4420     DecodeMOVHLPSMask(NumElems, Mask);
4421     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4422     break;
4423   case X86ISD::MOVLHPS:
4424     DecodeMOVLHPSMask(NumElems, Mask);
4425     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4426     break;
4427   case X86ISD::PALIGNR:
4428     ImmN = N->getOperand(N->getNumOperands()-1);
4429     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4430     break;
4431   case X86ISD::PSHUFD:
4432   case X86ISD::VPERMILPI:
4433     ImmN = N->getOperand(N->getNumOperands()-1);
4434     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4435     IsUnary = true;
4436     break;
4437   case X86ISD::PSHUFHW:
4438     ImmN = N->getOperand(N->getNumOperands()-1);
4439     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4440     IsUnary = true;
4441     break;
4442   case X86ISD::PSHUFLW:
4443     ImmN = N->getOperand(N->getNumOperands()-1);
4444     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4445     IsUnary = true;
4446     break;
4447   case X86ISD::PSHUFB: {
4448     IsUnary = true;
4449     SDValue MaskNode = N->getOperand(1);
4450     while (MaskNode->getOpcode() == ISD::BITCAST)
4451       MaskNode = MaskNode->getOperand(0);
4452
4453     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4454       // If we have a build-vector, then things are easy.
4455       EVT VT = MaskNode.getValueType();
4456       assert(VT.isVector() &&
4457              "Can't produce a non-vector with a build_vector!");
4458       if (!VT.isInteger())
4459         return false;
4460
4461       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4462
4463       SmallVector<uint64_t, 32> RawMask;
4464       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4465         SDValue Op = MaskNode->getOperand(i);
4466         if (Op->getOpcode() == ISD::UNDEF) {
4467           RawMask.push_back((uint64_t)SM_SentinelUndef);
4468           continue;
4469         }
4470         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4471         if (!CN)
4472           return false;
4473         APInt MaskElement = CN->getAPIntValue();
4474
4475         // We now have to decode the element which could be any integer size and
4476         // extract each byte of it.
4477         for (int j = 0; j < NumBytesPerElement; ++j) {
4478           // Note that this is x86 and so always little endian: the low byte is
4479           // the first byte of the mask.
4480           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4481           MaskElement = MaskElement.lshr(8);
4482         }
4483       }
4484       DecodePSHUFBMask(RawMask, Mask);
4485       break;
4486     }
4487
4488     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4489     if (!MaskLoad)
4490       return false;
4491
4492     SDValue Ptr = MaskLoad->getBasePtr();
4493     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4494         Ptr->getOpcode() == X86ISD::WrapperRIP)
4495       Ptr = Ptr->getOperand(0);
4496
4497     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4498     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4499       return false;
4500
4501     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4502       DecodePSHUFBMask(C, Mask);
4503       if (Mask.empty())
4504         return false;
4505       break;
4506     }
4507
4508     return false;
4509   }
4510   case X86ISD::VPERMI:
4511     ImmN = N->getOperand(N->getNumOperands()-1);
4512     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4513     IsUnary = true;
4514     break;
4515   case X86ISD::MOVSS:
4516   case X86ISD::MOVSD:
4517     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4518     break;
4519   case X86ISD::VPERM2X128:
4520     ImmN = N->getOperand(N->getNumOperands()-1);
4521     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4522     if (Mask.empty()) return false;
4523     // Mask only contains negative index if an element is zero.
4524     if (std::any_of(Mask.begin(), Mask.end(), 
4525                     [](int M){ return M == SM_SentinelZero; }))
4526       return false;
4527     break;
4528   case X86ISD::MOVSLDUP:
4529     DecodeMOVSLDUPMask(VT, Mask);
4530     IsUnary = true;
4531     break;
4532   case X86ISD::MOVSHDUP:
4533     DecodeMOVSHDUPMask(VT, Mask);
4534     IsUnary = true;
4535     break;
4536   case X86ISD::MOVDDUP:
4537     DecodeMOVDDUPMask(VT, Mask);
4538     IsUnary = true;
4539     break;
4540   case X86ISD::MOVLHPD:
4541   case X86ISD::MOVLPD:
4542   case X86ISD::MOVLPS:
4543     // Not yet implemented
4544     return false;
4545   default: llvm_unreachable("unknown target shuffle node");
4546   }
4547
4548   // If we have a fake unary shuffle, the shuffle mask is spread across two
4549   // inputs that are actually the same node. Re-map the mask to always point
4550   // into the first input.
4551   if (IsFakeUnary)
4552     for (int &M : Mask)
4553       if (M >= (int)Mask.size())
4554         M -= Mask.size();
4555
4556   return true;
4557 }
4558
4559 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4560 /// element of the result of the vector shuffle.
4561 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4562                                    unsigned Depth) {
4563   if (Depth == 6)
4564     return SDValue();  // Limit search depth.
4565
4566   SDValue V = SDValue(N, 0);
4567   EVT VT = V.getValueType();
4568   unsigned Opcode = V.getOpcode();
4569
4570   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4571   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4572     int Elt = SV->getMaskElt(Index);
4573
4574     if (Elt < 0)
4575       return DAG.getUNDEF(VT.getVectorElementType());
4576
4577     unsigned NumElems = VT.getVectorNumElements();
4578     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4579                                          : SV->getOperand(1);
4580     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4581   }
4582
4583   // Recurse into target specific vector shuffles to find scalars.
4584   if (isTargetShuffle(Opcode)) {
4585     MVT ShufVT = V.getSimpleValueType();
4586     unsigned NumElems = ShufVT.getVectorNumElements();
4587     SmallVector<int, 16> ShuffleMask;
4588     bool IsUnary;
4589
4590     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4591       return SDValue();
4592
4593     int Elt = ShuffleMask[Index];
4594     if (Elt < 0)
4595       return DAG.getUNDEF(ShufVT.getVectorElementType());
4596
4597     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4598                                          : N->getOperand(1);
4599     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4600                                Depth+1);
4601   }
4602
4603   // Actual nodes that may contain scalar elements
4604   if (Opcode == ISD::BITCAST) {
4605     V = V.getOperand(0);
4606     EVT SrcVT = V.getValueType();
4607     unsigned NumElems = VT.getVectorNumElements();
4608
4609     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4610       return SDValue();
4611   }
4612
4613   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4614     return (Index == 0) ? V.getOperand(0)
4615                         : DAG.getUNDEF(VT.getVectorElementType());
4616
4617   if (V.getOpcode() == ISD::BUILD_VECTOR)
4618     return V.getOperand(Index);
4619
4620   return SDValue();
4621 }
4622
4623 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4624 ///
4625 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4626                                        unsigned NumNonZero, unsigned NumZero,
4627                                        SelectionDAG &DAG,
4628                                        const X86Subtarget* Subtarget,
4629                                        const TargetLowering &TLI) {
4630   if (NumNonZero > 8)
4631     return SDValue();
4632
4633   SDLoc dl(Op);
4634   SDValue V;
4635   bool First = true;
4636
4637   // SSE4.1 - use PINSRB to insert each byte directly.
4638   if (Subtarget->hasSSE41()) {
4639     for (unsigned i = 0; i < 16; ++i) {
4640       bool isNonZero = (NonZeros & (1 << i)) != 0;
4641       if (isNonZero) {
4642         if (First) {
4643           if (NumZero)
4644             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4645           else
4646             V = DAG.getUNDEF(MVT::v16i8);
4647           First = false;
4648         }
4649         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4650                         MVT::v16i8, V, Op.getOperand(i),
4651                         DAG.getIntPtrConstant(i, dl));
4652       }
4653     }
4654
4655     return V;
4656   }
4657
4658   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4659   for (unsigned i = 0; i < 16; ++i) {
4660     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4661     if (ThisIsNonZero && First) {
4662       if (NumZero)
4663         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4664       else
4665         V = DAG.getUNDEF(MVT::v8i16);
4666       First = false;
4667     }
4668
4669     if ((i & 1) != 0) {
4670       SDValue ThisElt, LastElt;
4671       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4672       if (LastIsNonZero) {
4673         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4674                               MVT::i16, Op.getOperand(i-1));
4675       }
4676       if (ThisIsNonZero) {
4677         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4678         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4679                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4680         if (LastIsNonZero)
4681           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4682       } else
4683         ThisElt = LastElt;
4684
4685       if (ThisElt.getNode())
4686         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4687                         DAG.getIntPtrConstant(i/2, dl));
4688     }
4689   }
4690
4691   return DAG.getBitcast(MVT::v16i8, V);
4692 }
4693
4694 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4695 ///
4696 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4697                                      unsigned NumNonZero, unsigned NumZero,
4698                                      SelectionDAG &DAG,
4699                                      const X86Subtarget* Subtarget,
4700                                      const TargetLowering &TLI) {
4701   if (NumNonZero > 4)
4702     return SDValue();
4703
4704   SDLoc dl(Op);
4705   SDValue V;
4706   bool First = true;
4707   for (unsigned i = 0; i < 8; ++i) {
4708     bool isNonZero = (NonZeros & (1 << i)) != 0;
4709     if (isNonZero) {
4710       if (First) {
4711         if (NumZero)
4712           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4713         else
4714           V = DAG.getUNDEF(MVT::v8i16);
4715         First = false;
4716       }
4717       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4718                       MVT::v8i16, V, Op.getOperand(i),
4719                       DAG.getIntPtrConstant(i, dl));
4720     }
4721   }
4722
4723   return V;
4724 }
4725
4726 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4727 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4728                                      const X86Subtarget *Subtarget,
4729                                      const TargetLowering &TLI) {
4730   // Find all zeroable elements.
4731   std::bitset<4> Zeroable;
4732   for (int i=0; i < 4; ++i) {
4733     SDValue Elt = Op->getOperand(i);
4734     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4735   }
4736   assert(Zeroable.size() - Zeroable.count() > 1 &&
4737          "We expect at least two non-zero elements!");
4738
4739   // We only know how to deal with build_vector nodes where elements are either
4740   // zeroable or extract_vector_elt with constant index.
4741   SDValue FirstNonZero;
4742   unsigned FirstNonZeroIdx;
4743   for (unsigned i=0; i < 4; ++i) {
4744     if (Zeroable[i])
4745       continue;
4746     SDValue Elt = Op->getOperand(i);
4747     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4748         !isa<ConstantSDNode>(Elt.getOperand(1)))
4749       return SDValue();
4750     // Make sure that this node is extracting from a 128-bit vector.
4751     MVT VT = Elt.getOperand(0).getSimpleValueType();
4752     if (!VT.is128BitVector())
4753       return SDValue();
4754     if (!FirstNonZero.getNode()) {
4755       FirstNonZero = Elt;
4756       FirstNonZeroIdx = i;
4757     }
4758   }
4759
4760   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4761   SDValue V1 = FirstNonZero.getOperand(0);
4762   MVT VT = V1.getSimpleValueType();
4763
4764   // See if this build_vector can be lowered as a blend with zero.
4765   SDValue Elt;
4766   unsigned EltMaskIdx, EltIdx;
4767   int Mask[4];
4768   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4769     if (Zeroable[EltIdx]) {
4770       // The zero vector will be on the right hand side.
4771       Mask[EltIdx] = EltIdx+4;
4772       continue;
4773     }
4774
4775     Elt = Op->getOperand(EltIdx);
4776     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4777     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4778     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4779       break;
4780     Mask[EltIdx] = EltIdx;
4781   }
4782
4783   if (EltIdx == 4) {
4784     // Let the shuffle legalizer deal with blend operations.
4785     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4786     if (V1.getSimpleValueType() != VT)
4787       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4788     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4789   }
4790
4791   // See if we can lower this build_vector to a INSERTPS.
4792   if (!Subtarget->hasSSE41())
4793     return SDValue();
4794
4795   SDValue V2 = Elt.getOperand(0);
4796   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4797     V1 = SDValue();
4798
4799   bool CanFold = true;
4800   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4801     if (Zeroable[i])
4802       continue;
4803
4804     SDValue Current = Op->getOperand(i);
4805     SDValue SrcVector = Current->getOperand(0);
4806     if (!V1.getNode())
4807       V1 = SrcVector;
4808     CanFold = SrcVector == V1 &&
4809       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4810   }
4811
4812   if (!CanFold)
4813     return SDValue();
4814
4815   assert(V1.getNode() && "Expected at least two non-zero elements!");
4816   if (V1.getSimpleValueType() != MVT::v4f32)
4817     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4818   if (V2.getSimpleValueType() != MVT::v4f32)
4819     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4820
4821   // Ok, we can emit an INSERTPS instruction.
4822   unsigned ZMask = Zeroable.to_ulong();
4823
4824   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4825   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4826   SDLoc DL(Op);
4827   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4828                                DAG.getIntPtrConstant(InsertPSMask, DL));
4829   return DAG.getBitcast(VT, Result);
4830 }
4831
4832 /// Return a vector logical shift node.
4833 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4834                          unsigned NumBits, SelectionDAG &DAG,
4835                          const TargetLowering &TLI, SDLoc dl) {
4836   assert(VT.is128BitVector() && "Unknown type for VShift");
4837   MVT ShVT = MVT::v2i64;
4838   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4839   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4840   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4841   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4842   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4843   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4844 }
4845
4846 static SDValue
4847 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4848
4849   // Check if the scalar load can be widened into a vector load. And if
4850   // the address is "base + cst" see if the cst can be "absorbed" into
4851   // the shuffle mask.
4852   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4853     SDValue Ptr = LD->getBasePtr();
4854     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4855       return SDValue();
4856     EVT PVT = LD->getValueType(0);
4857     if (PVT != MVT::i32 && PVT != MVT::f32)
4858       return SDValue();
4859
4860     int FI = -1;
4861     int64_t Offset = 0;
4862     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4863       FI = FINode->getIndex();
4864       Offset = 0;
4865     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4866                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4867       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4868       Offset = Ptr.getConstantOperandVal(1);
4869       Ptr = Ptr.getOperand(0);
4870     } else {
4871       return SDValue();
4872     }
4873
4874     // FIXME: 256-bit vector instructions don't require a strict alignment,
4875     // improve this code to support it better.
4876     unsigned RequiredAlign = VT.getSizeInBits()/8;
4877     SDValue Chain = LD->getChain();
4878     // Make sure the stack object alignment is at least 16 or 32.
4879     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4880     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4881       if (MFI->isFixedObjectIndex(FI)) {
4882         // Can't change the alignment. FIXME: It's possible to compute
4883         // the exact stack offset and reference FI + adjust offset instead.
4884         // If someone *really* cares about this. That's the way to implement it.
4885         return SDValue();
4886       } else {
4887         MFI->setObjectAlignment(FI, RequiredAlign);
4888       }
4889     }
4890
4891     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4892     // Ptr + (Offset & ~15).
4893     if (Offset < 0)
4894       return SDValue();
4895     if ((Offset % RequiredAlign) & 3)
4896       return SDValue();
4897     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4898     if (StartOffset) {
4899       SDLoc DL(Ptr);
4900       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4901                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4902     }
4903
4904     int EltNo = (Offset - StartOffset) >> 2;
4905     unsigned NumElems = VT.getVectorNumElements();
4906
4907     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4908     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4909                              LD->getPointerInfo().getWithOffset(StartOffset),
4910                              false, false, false, 0);
4911
4912     SmallVector<int, 8> Mask(NumElems, EltNo);
4913
4914     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4915   }
4916
4917   return SDValue();
4918 }
4919
4920 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4921 /// elements can be replaced by a single large load which has the same value as
4922 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4923 ///
4924 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4925 ///
4926 /// FIXME: we'd also like to handle the case where the last elements are zero
4927 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4928 /// There's even a handy isZeroNode for that purpose.
4929 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4930                                         SDLoc &DL, SelectionDAG &DAG,
4931                                         bool isAfterLegalize) {
4932   unsigned NumElems = Elts.size();
4933
4934   LoadSDNode *LDBase = nullptr;
4935   unsigned LastLoadedElt = -1U;
4936
4937   // For each element in the initializer, see if we've found a load or an undef.
4938   // If we don't find an initial load element, or later load elements are
4939   // non-consecutive, bail out.
4940   for (unsigned i = 0; i < NumElems; ++i) {
4941     SDValue Elt = Elts[i];
4942     // Look through a bitcast.
4943     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4944       Elt = Elt.getOperand(0);
4945     if (!Elt.getNode() ||
4946         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4947       return SDValue();
4948     if (!LDBase) {
4949       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4950         return SDValue();
4951       LDBase = cast<LoadSDNode>(Elt.getNode());
4952       LastLoadedElt = i;
4953       continue;
4954     }
4955     if (Elt.getOpcode() == ISD::UNDEF)
4956       continue;
4957
4958     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4959     EVT LdVT = Elt.getValueType();
4960     // Each loaded element must be the correct fractional portion of the
4961     // requested vector load.
4962     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4963       return SDValue();
4964     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4965       return SDValue();
4966     LastLoadedElt = i;
4967   }
4968
4969   // If we have found an entire vector of loads and undefs, then return a large
4970   // load of the entire vector width starting at the base pointer.  If we found
4971   // consecutive loads for the low half, generate a vzext_load node.
4972   if (LastLoadedElt == NumElems - 1) {
4973     assert(LDBase && "Did not find base load for merging consecutive loads");
4974     EVT EltVT = LDBase->getValueType(0);
4975     // Ensure that the input vector size for the merged loads matches the
4976     // cumulative size of the input elements.
4977     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4978       return SDValue();
4979
4980     if (isAfterLegalize &&
4981         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4982       return SDValue();
4983
4984     SDValue NewLd = SDValue();
4985
4986     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4987                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4988                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4989                         LDBase->getAlignment());
4990
4991     if (LDBase->hasAnyUseOfValue(1)) {
4992       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4993                                      SDValue(LDBase, 1),
4994                                      SDValue(NewLd.getNode(), 1));
4995       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4996       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4997                              SDValue(NewLd.getNode(), 1));
4998     }
4999
5000     return NewLd;
5001   }
5002
5003   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5004   //of a v4i32 / v4f32. It's probably worth generalizing.
5005   EVT EltVT = VT.getVectorElementType();
5006   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5007       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5008     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5009     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5010     SDValue ResNode =
5011         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5012                                 LDBase->getPointerInfo(),
5013                                 LDBase->getAlignment(),
5014                                 false/*isVolatile*/, true/*ReadMem*/,
5015                                 false/*WriteMem*/);
5016
5017     // Make sure the newly-created LOAD is in the same position as LDBase in
5018     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5019     // update uses of LDBase's output chain to use the TokenFactor.
5020     if (LDBase->hasAnyUseOfValue(1)) {
5021       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5022                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5023       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5024       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5025                              SDValue(ResNode.getNode(), 1));
5026     }
5027
5028     return DAG.getBitcast(VT, ResNode);
5029   }
5030   return SDValue();
5031 }
5032
5033 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5034 /// to generate a splat value for the following cases:
5035 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5036 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5037 /// a scalar load, or a constant.
5038 /// The VBROADCAST node is returned when a pattern is found,
5039 /// or SDValue() otherwise.
5040 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5041                                     SelectionDAG &DAG) {
5042   // VBROADCAST requires AVX.
5043   // TODO: Splats could be generated for non-AVX CPUs using SSE
5044   // instructions, but there's less potential gain for only 128-bit vectors.
5045   if (!Subtarget->hasAVX())
5046     return SDValue();
5047
5048   MVT VT = Op.getSimpleValueType();
5049   SDLoc dl(Op);
5050
5051   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5052          "Unsupported vector type for broadcast.");
5053
5054   SDValue Ld;
5055   bool ConstSplatVal;
5056
5057   switch (Op.getOpcode()) {
5058     default:
5059       // Unknown pattern found.
5060       return SDValue();
5061
5062     case ISD::BUILD_VECTOR: {
5063       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5064       BitVector UndefElements;
5065       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5066
5067       // We need a splat of a single value to use broadcast, and it doesn't
5068       // make any sense if the value is only in one element of the vector.
5069       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5070         return SDValue();
5071
5072       Ld = Splat;
5073       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5074                        Ld.getOpcode() == ISD::ConstantFP);
5075
5076       // Make sure that all of the users of a non-constant load are from the
5077       // BUILD_VECTOR node.
5078       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5079         return SDValue();
5080       break;
5081     }
5082
5083     case ISD::VECTOR_SHUFFLE: {
5084       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5085
5086       // Shuffles must have a splat mask where the first element is
5087       // broadcasted.
5088       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5089         return SDValue();
5090
5091       SDValue Sc = Op.getOperand(0);
5092       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5093           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5094
5095         if (!Subtarget->hasInt256())
5096           return SDValue();
5097
5098         // Use the register form of the broadcast instruction available on AVX2.
5099         if (VT.getSizeInBits() >= 256)
5100           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5101         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5102       }
5103
5104       Ld = Sc.getOperand(0);
5105       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5106                        Ld.getOpcode() == ISD::ConstantFP);
5107
5108       // The scalar_to_vector node and the suspected
5109       // load node must have exactly one user.
5110       // Constants may have multiple users.
5111
5112       // AVX-512 has register version of the broadcast
5113       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5114         Ld.getValueType().getSizeInBits() >= 32;
5115       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5116           !hasRegVer))
5117         return SDValue();
5118       break;
5119     }
5120   }
5121
5122   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5123   bool IsGE256 = (VT.getSizeInBits() >= 256);
5124
5125   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5126   // instruction to save 8 or more bytes of constant pool data.
5127   // TODO: If multiple splats are generated to load the same constant,
5128   // it may be detrimental to overall size. There needs to be a way to detect
5129   // that condition to know if this is truly a size win.
5130   const Function *F = DAG.getMachineFunction().getFunction();
5131   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5132
5133   // Handle broadcasting a single constant scalar from the constant pool
5134   // into a vector.
5135   // On Sandybridge (no AVX2), it is still better to load a constant vector
5136   // from the constant pool and not to broadcast it from a scalar.
5137   // But override that restriction when optimizing for size.
5138   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5139   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5140     EVT CVT = Ld.getValueType();
5141     assert(!CVT.isVector() && "Must not broadcast a vector type");
5142
5143     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5144     // For size optimization, also splat v2f64 and v2i64, and for size opt
5145     // with AVX2, also splat i8 and i16.
5146     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5147     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5148         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5149       const Constant *C = nullptr;
5150       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5151         C = CI->getConstantIntValue();
5152       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5153         C = CF->getConstantFPValue();
5154
5155       assert(C && "Invalid constant type");
5156
5157       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5158       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5159       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5160       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5161                        MachinePointerInfo::getConstantPool(),
5162                        false, false, false, Alignment);
5163
5164       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5165     }
5166   }
5167
5168   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5169
5170   // Handle AVX2 in-register broadcasts.
5171   if (!IsLoad && Subtarget->hasInt256() &&
5172       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5173     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5174
5175   // The scalar source must be a normal load.
5176   if (!IsLoad)
5177     return SDValue();
5178
5179   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5180       (Subtarget->hasVLX() && ScalarSize == 64))
5181     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5182
5183   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5184   // double since there is no vbroadcastsd xmm
5185   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5186     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5187       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5188   }
5189
5190   // Unsupported broadcast.
5191   return SDValue();
5192 }
5193
5194 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5195 /// underlying vector and index.
5196 ///
5197 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5198 /// index.
5199 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5200                                          SDValue ExtIdx) {
5201   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5202   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5203     return Idx;
5204
5205   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5206   // lowered this:
5207   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5208   // to:
5209   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5210   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5211   //                           undef)
5212   //                       Constant<0>)
5213   // In this case the vector is the extract_subvector expression and the index
5214   // is 2, as specified by the shuffle.
5215   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5216   SDValue ShuffleVec = SVOp->getOperand(0);
5217   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5218   assert(ShuffleVecVT.getVectorElementType() ==
5219          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5220
5221   int ShuffleIdx = SVOp->getMaskElt(Idx);
5222   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5223     ExtractedFromVec = ShuffleVec;
5224     return ShuffleIdx;
5225   }
5226   return Idx;
5227 }
5228
5229 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5230   MVT VT = Op.getSimpleValueType();
5231
5232   // Skip if insert_vec_elt is not supported.
5233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5234   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5235     return SDValue();
5236
5237   SDLoc DL(Op);
5238   unsigned NumElems = Op.getNumOperands();
5239
5240   SDValue VecIn1;
5241   SDValue VecIn2;
5242   SmallVector<unsigned, 4> InsertIndices;
5243   SmallVector<int, 8> Mask(NumElems, -1);
5244
5245   for (unsigned i = 0; i != NumElems; ++i) {
5246     unsigned Opc = Op.getOperand(i).getOpcode();
5247
5248     if (Opc == ISD::UNDEF)
5249       continue;
5250
5251     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5252       // Quit if more than 1 elements need inserting.
5253       if (InsertIndices.size() > 1)
5254         return SDValue();
5255
5256       InsertIndices.push_back(i);
5257       continue;
5258     }
5259
5260     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5261     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5262     // Quit if non-constant index.
5263     if (!isa<ConstantSDNode>(ExtIdx))
5264       return SDValue();
5265     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5266
5267     // Quit if extracted from vector of different type.
5268     if (ExtractedFromVec.getValueType() != VT)
5269       return SDValue();
5270
5271     if (!VecIn1.getNode())
5272       VecIn1 = ExtractedFromVec;
5273     else if (VecIn1 != ExtractedFromVec) {
5274       if (!VecIn2.getNode())
5275         VecIn2 = ExtractedFromVec;
5276       else if (VecIn2 != ExtractedFromVec)
5277         // Quit if more than 2 vectors to shuffle
5278         return SDValue();
5279     }
5280
5281     if (ExtractedFromVec == VecIn1)
5282       Mask[i] = Idx;
5283     else if (ExtractedFromVec == VecIn2)
5284       Mask[i] = Idx + NumElems;
5285   }
5286
5287   if (!VecIn1.getNode())
5288     return SDValue();
5289
5290   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5291   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5292   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5293     unsigned Idx = InsertIndices[i];
5294     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5295                      DAG.getIntPtrConstant(Idx, DL));
5296   }
5297
5298   return NV;
5299 }
5300
5301 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5302   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5303          Op.getScalarValueSizeInBits() == 1 &&
5304          "Can not convert non-constant vector");
5305   uint64_t Immediate = 0;
5306   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5307     SDValue In = Op.getOperand(idx);
5308     if (In.getOpcode() != ISD::UNDEF)
5309       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5310   }
5311   SDLoc dl(Op);
5312   MVT VT =
5313    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5314   return DAG.getConstant(Immediate, dl, VT);
5315 }
5316 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5317 SDValue
5318 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5319
5320   MVT VT = Op.getSimpleValueType();
5321   assert((VT.getVectorElementType() == MVT::i1) &&
5322          "Unexpected type in LowerBUILD_VECTORvXi1!");
5323
5324   SDLoc dl(Op);
5325   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5326     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5327     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5328     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5329   }
5330
5331   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5332     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5333     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5334     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5335   }
5336
5337   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5338     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5339     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5340       return DAG.getBitcast(VT, Imm);
5341     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5342     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5343                         DAG.getIntPtrConstant(0, dl));
5344   }
5345
5346   // Vector has one or more non-const elements
5347   uint64_t Immediate = 0;
5348   SmallVector<unsigned, 16> NonConstIdx;
5349   bool IsSplat = true;
5350   bool HasConstElts = false;
5351   int SplatIdx = -1;
5352   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5353     SDValue In = Op.getOperand(idx);
5354     if (In.getOpcode() == ISD::UNDEF)
5355       continue;
5356     if (!isa<ConstantSDNode>(In))
5357       NonConstIdx.push_back(idx);
5358     else {
5359       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5360       HasConstElts = true;
5361     }
5362     if (SplatIdx == -1)
5363       SplatIdx = idx;
5364     else if (In != Op.getOperand(SplatIdx))
5365       IsSplat = false;
5366   }
5367
5368   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5369   if (IsSplat)
5370     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5371                        DAG.getConstant(1, dl, VT),
5372                        DAG.getConstant(0, dl, VT));
5373
5374   // insert elements one by one
5375   SDValue DstVec;
5376   SDValue Imm;
5377   if (Immediate) {
5378     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5379     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5380   }
5381   else if (HasConstElts)
5382     Imm = DAG.getConstant(0, dl, VT);
5383   else
5384     Imm = DAG.getUNDEF(VT);
5385   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5386     DstVec = DAG.getBitcast(VT, Imm);
5387   else {
5388     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5389     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5390                          DAG.getIntPtrConstant(0, dl));
5391   }
5392
5393   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5394     unsigned InsertIdx = NonConstIdx[i];
5395     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5396                          Op.getOperand(InsertIdx),
5397                          DAG.getIntPtrConstant(InsertIdx, dl));
5398   }
5399   return DstVec;
5400 }
5401
5402 /// \brief Return true if \p N implements a horizontal binop and return the
5403 /// operands for the horizontal binop into V0 and V1.
5404 ///
5405 /// This is a helper function of LowerToHorizontalOp().
5406 /// This function checks that the build_vector \p N in input implements a
5407 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5408 /// operation to match.
5409 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5410 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5411 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5412 /// arithmetic sub.
5413 ///
5414 /// This function only analyzes elements of \p N whose indices are
5415 /// in range [BaseIdx, LastIdx).
5416 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5417                               SelectionDAG &DAG,
5418                               unsigned BaseIdx, unsigned LastIdx,
5419                               SDValue &V0, SDValue &V1) {
5420   EVT VT = N->getValueType(0);
5421
5422   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5423   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5424          "Invalid Vector in input!");
5425
5426   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5427   bool CanFold = true;
5428   unsigned ExpectedVExtractIdx = BaseIdx;
5429   unsigned NumElts = LastIdx - BaseIdx;
5430   V0 = DAG.getUNDEF(VT);
5431   V1 = DAG.getUNDEF(VT);
5432
5433   // Check if N implements a horizontal binop.
5434   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5435     SDValue Op = N->getOperand(i + BaseIdx);
5436
5437     // Skip UNDEFs.
5438     if (Op->getOpcode() == ISD::UNDEF) {
5439       // Update the expected vector extract index.
5440       if (i * 2 == NumElts)
5441         ExpectedVExtractIdx = BaseIdx;
5442       ExpectedVExtractIdx += 2;
5443       continue;
5444     }
5445
5446     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5447
5448     if (!CanFold)
5449       break;
5450
5451     SDValue Op0 = Op.getOperand(0);
5452     SDValue Op1 = Op.getOperand(1);
5453
5454     // Try to match the following pattern:
5455     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5456     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5457         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5458         Op0.getOperand(0) == Op1.getOperand(0) &&
5459         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5460         isa<ConstantSDNode>(Op1.getOperand(1)));
5461     if (!CanFold)
5462       break;
5463
5464     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5465     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5466
5467     if (i * 2 < NumElts) {
5468       if (V0.getOpcode() == ISD::UNDEF) {
5469         V0 = Op0.getOperand(0);
5470         if (V0.getValueType() != VT)
5471           return false;
5472       }
5473     } else {
5474       if (V1.getOpcode() == ISD::UNDEF) {
5475         V1 = Op0.getOperand(0);
5476         if (V1.getValueType() != VT)
5477           return false;
5478       }
5479       if (i * 2 == NumElts)
5480         ExpectedVExtractIdx = BaseIdx;
5481     }
5482
5483     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5484     if (I0 == ExpectedVExtractIdx)
5485       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5486     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5487       // Try to match the following dag sequence:
5488       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5489       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5490     } else
5491       CanFold = false;
5492
5493     ExpectedVExtractIdx += 2;
5494   }
5495
5496   return CanFold;
5497 }
5498
5499 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5500 /// a concat_vector.
5501 ///
5502 /// This is a helper function of LowerToHorizontalOp().
5503 /// This function expects two 256-bit vectors called V0 and V1.
5504 /// At first, each vector is split into two separate 128-bit vectors.
5505 /// Then, the resulting 128-bit vectors are used to implement two
5506 /// horizontal binary operations.
5507 ///
5508 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5509 ///
5510 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5511 /// the two new horizontal binop.
5512 /// When Mode is set, the first horizontal binop dag node would take as input
5513 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5514 /// horizontal binop dag node would take as input the lower 128-bit of V1
5515 /// and the upper 128-bit of V1.
5516 ///   Example:
5517 ///     HADD V0_LO, V0_HI
5518 ///     HADD V1_LO, V1_HI
5519 ///
5520 /// Otherwise, the first horizontal binop dag node takes as input the lower
5521 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5522 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5523 ///   Example:
5524 ///     HADD V0_LO, V1_LO
5525 ///     HADD V0_HI, V1_HI
5526 ///
5527 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5528 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5529 /// the upper 128-bits of the result.
5530 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5531                                      SDLoc DL, SelectionDAG &DAG,
5532                                      unsigned X86Opcode, bool Mode,
5533                                      bool isUndefLO, bool isUndefHI) {
5534   EVT VT = V0.getValueType();
5535   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5536          "Invalid nodes in input!");
5537
5538   unsigned NumElts = VT.getVectorNumElements();
5539   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5540   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5541   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5542   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5543   EVT NewVT = V0_LO.getValueType();
5544
5545   SDValue LO = DAG.getUNDEF(NewVT);
5546   SDValue HI = DAG.getUNDEF(NewVT);
5547
5548   if (Mode) {
5549     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5550     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5551       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5552     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5553       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5554   } else {
5555     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5556     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5557                        V1_LO->getOpcode() != ISD::UNDEF))
5558       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5559
5560     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5561                        V1_HI->getOpcode() != ISD::UNDEF))
5562       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5563   }
5564
5565   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5566 }
5567
5568 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5569 /// node.
5570 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5571                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5572   EVT VT = BV->getValueType(0);
5573   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5574       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5575     return SDValue();
5576
5577   SDLoc DL(BV);
5578   unsigned NumElts = VT.getVectorNumElements();
5579   SDValue InVec0 = DAG.getUNDEF(VT);
5580   SDValue InVec1 = DAG.getUNDEF(VT);
5581
5582   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5583           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5584
5585   // Odd-numbered elements in the input build vector are obtained from
5586   // adding two integer/float elements.
5587   // Even-numbered elements in the input build vector are obtained from
5588   // subtracting two integer/float elements.
5589   unsigned ExpectedOpcode = ISD::FSUB;
5590   unsigned NextExpectedOpcode = ISD::FADD;
5591   bool AddFound = false;
5592   bool SubFound = false;
5593
5594   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5595     SDValue Op = BV->getOperand(i);
5596
5597     // Skip 'undef' values.
5598     unsigned Opcode = Op.getOpcode();
5599     if (Opcode == ISD::UNDEF) {
5600       std::swap(ExpectedOpcode, NextExpectedOpcode);
5601       continue;
5602     }
5603
5604     // Early exit if we found an unexpected opcode.
5605     if (Opcode != ExpectedOpcode)
5606       return SDValue();
5607
5608     SDValue Op0 = Op.getOperand(0);
5609     SDValue Op1 = Op.getOperand(1);
5610
5611     // Try to match the following pattern:
5612     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5613     // Early exit if we cannot match that sequence.
5614     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5615         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5616         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5617         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5618         Op0.getOperand(1) != Op1.getOperand(1))
5619       return SDValue();
5620
5621     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5622     if (I0 != i)
5623       return SDValue();
5624
5625     // We found a valid add/sub node. Update the information accordingly.
5626     if (i & 1)
5627       AddFound = true;
5628     else
5629       SubFound = true;
5630
5631     // Update InVec0 and InVec1.
5632     if (InVec0.getOpcode() == ISD::UNDEF) {
5633       InVec0 = Op0.getOperand(0);
5634       if (InVec0.getValueType() != VT)
5635         return SDValue();
5636     }
5637     if (InVec1.getOpcode() == ISD::UNDEF) {
5638       InVec1 = Op1.getOperand(0);
5639       if (InVec1.getValueType() != VT)
5640         return SDValue();
5641     }
5642
5643     // Make sure that operands in input to each add/sub node always
5644     // come from a same pair of vectors.
5645     if (InVec0 != Op0.getOperand(0)) {
5646       if (ExpectedOpcode == ISD::FSUB)
5647         return SDValue();
5648
5649       // FADD is commutable. Try to commute the operands
5650       // and then test again.
5651       std::swap(Op0, Op1);
5652       if (InVec0 != Op0.getOperand(0))
5653         return SDValue();
5654     }
5655
5656     if (InVec1 != Op1.getOperand(0))
5657       return SDValue();
5658
5659     // Update the pair of expected opcodes.
5660     std::swap(ExpectedOpcode, NextExpectedOpcode);
5661   }
5662
5663   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5664   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5665       InVec1.getOpcode() != ISD::UNDEF)
5666     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5667
5668   return SDValue();
5669 }
5670
5671 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5672 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5673                                    const X86Subtarget *Subtarget,
5674                                    SelectionDAG &DAG) {
5675   EVT VT = BV->getValueType(0);
5676   unsigned NumElts = VT.getVectorNumElements();
5677   unsigned NumUndefsLO = 0;
5678   unsigned NumUndefsHI = 0;
5679   unsigned Half = NumElts/2;
5680
5681   // Count the number of UNDEF operands in the build_vector in input.
5682   for (unsigned i = 0, e = Half; i != e; ++i)
5683     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5684       NumUndefsLO++;
5685
5686   for (unsigned i = Half, e = NumElts; i != e; ++i)
5687     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5688       NumUndefsHI++;
5689
5690   // Early exit if this is either a build_vector of all UNDEFs or all the
5691   // operands but one are UNDEF.
5692   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5693     return SDValue();
5694
5695   SDLoc DL(BV);
5696   SDValue InVec0, InVec1;
5697   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5698     // Try to match an SSE3 float HADD/HSUB.
5699     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5700       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5701
5702     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5703       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5704   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5705     // Try to match an SSSE3 integer HADD/HSUB.
5706     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5707       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5708
5709     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5710       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5711   }
5712
5713   if (!Subtarget->hasAVX())
5714     return SDValue();
5715
5716   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5717     // Try to match an AVX horizontal add/sub of packed single/double
5718     // precision floating point values from 256-bit vectors.
5719     SDValue InVec2, InVec3;
5720     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5721         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5722         ((InVec0.getOpcode() == ISD::UNDEF ||
5723           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5724         ((InVec1.getOpcode() == ISD::UNDEF ||
5725           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5726       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5727
5728     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5729         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5730         ((InVec0.getOpcode() == ISD::UNDEF ||
5731           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5732         ((InVec1.getOpcode() == ISD::UNDEF ||
5733           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5734       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5735   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5736     // Try to match an AVX2 horizontal add/sub of signed integers.
5737     SDValue InVec2, InVec3;
5738     unsigned X86Opcode;
5739     bool CanFold = true;
5740
5741     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5742         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5743         ((InVec0.getOpcode() == ISD::UNDEF ||
5744           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5745         ((InVec1.getOpcode() == ISD::UNDEF ||
5746           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5747       X86Opcode = X86ISD::HADD;
5748     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5749         isHorizontalBinOp(BV, ISD::SUB, 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::HSUB;
5755     else
5756       CanFold = false;
5757
5758     if (CanFold) {
5759       // Fold this build_vector into a single horizontal add/sub.
5760       // Do this only if the target has AVX2.
5761       if (Subtarget->hasAVX2())
5762         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5763
5764       // Do not try to expand this build_vector into a pair of horizontal
5765       // add/sub if we can emit a pair of scalar add/sub.
5766       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5767         return SDValue();
5768
5769       // Convert this build_vector into a pair of horizontal binop followed by
5770       // a concat vector.
5771       bool isUndefLO = NumUndefsLO == Half;
5772       bool isUndefHI = NumUndefsHI == Half;
5773       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5774                                    isUndefLO, isUndefHI);
5775     }
5776   }
5777
5778   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5779        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5780     unsigned X86Opcode;
5781     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5782       X86Opcode = X86ISD::HADD;
5783     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5784       X86Opcode = X86ISD::HSUB;
5785     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5786       X86Opcode = X86ISD::FHADD;
5787     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5788       X86Opcode = X86ISD::FHSUB;
5789     else
5790       return SDValue();
5791
5792     // Don't try to expand this build_vector into a pair of horizontal add/sub
5793     // if we can simply emit a pair of scalar add/sub.
5794     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5795       return SDValue();
5796
5797     // Convert this build_vector into two horizontal add/sub followed by
5798     // a concat vector.
5799     bool isUndefLO = NumUndefsLO == Half;
5800     bool isUndefHI = NumUndefsHI == Half;
5801     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5802                                  isUndefLO, isUndefHI);
5803   }
5804
5805   return SDValue();
5806 }
5807
5808 SDValue
5809 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5810   SDLoc dl(Op);
5811
5812   MVT VT = Op.getSimpleValueType();
5813   MVT ExtVT = VT.getVectorElementType();
5814   unsigned NumElems = Op.getNumOperands();
5815
5816   // Generate vectors for predicate vectors.
5817   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5818     return LowerBUILD_VECTORvXi1(Op, DAG);
5819
5820   // Vectors containing all zeros can be matched by pxor and xorps later
5821   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5822     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5823     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5824     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5825       return Op;
5826
5827     return getZeroVector(VT, Subtarget, DAG, dl);
5828   }
5829
5830   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5831   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5832   // vpcmpeqd on 256-bit vectors.
5833   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5834     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5835       return Op;
5836
5837     if (!VT.is512BitVector())
5838       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5839   }
5840
5841   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5842   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5843     return AddSub;
5844   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5845     return HorizontalOp;
5846   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5847     return Broadcast;
5848
5849   unsigned EVTBits = ExtVT.getSizeInBits();
5850
5851   unsigned NumZero  = 0;
5852   unsigned NumNonZero = 0;
5853   unsigned NonZeros = 0;
5854   bool IsAllConstants = true;
5855   SmallSet<SDValue, 8> Values;
5856   for (unsigned i = 0; i < NumElems; ++i) {
5857     SDValue Elt = Op.getOperand(i);
5858     if (Elt.getOpcode() == ISD::UNDEF)
5859       continue;
5860     Values.insert(Elt);
5861     if (Elt.getOpcode() != ISD::Constant &&
5862         Elt.getOpcode() != ISD::ConstantFP)
5863       IsAllConstants = false;
5864     if (X86::isZeroNode(Elt))
5865       NumZero++;
5866     else {
5867       NonZeros |= (1 << i);
5868       NumNonZero++;
5869     }
5870   }
5871
5872   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5873   if (NumNonZero == 0)
5874     return DAG.getUNDEF(VT);
5875
5876   // Special case for single non-zero, non-undef, element.
5877   if (NumNonZero == 1) {
5878     unsigned Idx = countTrailingZeros(NonZeros);
5879     SDValue Item = Op.getOperand(Idx);
5880
5881     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5882     // the value are obviously zero, truncate the value to i32 and do the
5883     // insertion that way.  Only do this if the value is non-constant or if the
5884     // value is a constant being inserted into element 0.  It is cheaper to do
5885     // a constant pool load than it is to do a movd + shuffle.
5886     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5887         (!IsAllConstants || Idx == 0)) {
5888       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5889         // Handle SSE only.
5890         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5891         EVT VecVT = MVT::v4i32;
5892
5893         // Truncate the value (which may itself be a constant) to i32, and
5894         // convert it to a vector with movd (S2V+shuffle to zero extend).
5895         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5896         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5897         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5898                                       Item, Idx * 2, true, Subtarget, DAG));
5899       }
5900     }
5901
5902     // If we have a constant or non-constant insertion into the low element of
5903     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5904     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5905     // depending on what the source datatype is.
5906     if (Idx == 0) {
5907       if (NumZero == 0)
5908         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5909
5910       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5911           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5912         if (VT.is512BitVector()) {
5913           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5914           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5915                              Item, DAG.getIntPtrConstant(0, dl));
5916         }
5917         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5918                "Expected an SSE value type!");
5919         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5920         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5921         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5922       }
5923
5924       // We can't directly insert an i8 or i16 into a vector, so zero extend
5925       // it to i32 first.
5926       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5927         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5928         if (VT.is256BitVector()) {
5929           if (Subtarget->hasAVX()) {
5930             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5931             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5932           } else {
5933             // Without AVX, we need to extend to a 128-bit vector and then
5934             // insert into the 256-bit vector.
5935             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5936             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5937             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5938           }
5939         } else {
5940           assert(VT.is128BitVector() && "Expected an SSE value type!");
5941           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5942           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5943         }
5944         return DAG.getBitcast(VT, Item);
5945       }
5946     }
5947
5948     // Is it a vector logical left shift?
5949     if (NumElems == 2 && Idx == 1 &&
5950         X86::isZeroNode(Op.getOperand(0)) &&
5951         !X86::isZeroNode(Op.getOperand(1))) {
5952       unsigned NumBits = VT.getSizeInBits();
5953       return getVShift(true, VT,
5954                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5955                                    VT, Op.getOperand(1)),
5956                        NumBits/2, DAG, *this, dl);
5957     }
5958
5959     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5960       return SDValue();
5961
5962     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5963     // is a non-constant being inserted into an element other than the low one,
5964     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5965     // movd/movss) to move this into the low element, then shuffle it into
5966     // place.
5967     if (EVTBits == 32) {
5968       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5969       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5970     }
5971   }
5972
5973   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5974   if (Values.size() == 1) {
5975     if (EVTBits == 32) {
5976       // Instead of a shuffle like this:
5977       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5978       // Check if it's possible to issue this instead.
5979       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5980       unsigned Idx = countTrailingZeros(NonZeros);
5981       SDValue Item = Op.getOperand(Idx);
5982       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5983         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5984     }
5985     return SDValue();
5986   }
5987
5988   // A vector full of immediates; various special cases are already
5989   // handled, so this is best done with a single constant-pool load.
5990   if (IsAllConstants)
5991     return SDValue();
5992
5993   // For AVX-length vectors, see if we can use a vector load to get all of the
5994   // elements, otherwise build the individual 128-bit pieces and use
5995   // shuffles to put them in place.
5996   if (VT.is256BitVector() || VT.is512BitVector()) {
5997     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5998
5999     // Check for a build vector of consecutive loads.
6000     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6001       return LD;
6002
6003     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6004
6005     // Build both the lower and upper subvector.
6006     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6007                                 makeArrayRef(&V[0], NumElems/2));
6008     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6009                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6010
6011     // Recreate the wider vector with the lower and upper part.
6012     if (VT.is256BitVector())
6013       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6014     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6015   }
6016
6017   // Let legalizer expand 2-wide build_vectors.
6018   if (EVTBits == 64) {
6019     if (NumNonZero == 1) {
6020       // One half is zero or undef.
6021       unsigned Idx = countTrailingZeros(NonZeros);
6022       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6023                                  Op.getOperand(Idx));
6024       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6025     }
6026     return SDValue();
6027   }
6028
6029   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6030   if (EVTBits == 8 && NumElems == 16)
6031     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6032                                         Subtarget, *this))
6033       return V;
6034
6035   if (EVTBits == 16 && NumElems == 8)
6036     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6037                                       Subtarget, *this))
6038       return V;
6039
6040   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6041   if (EVTBits == 32 && NumElems == 4)
6042     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6043       return V;
6044
6045   // If element VT is == 32 bits, turn it into a number of shuffles.
6046   SmallVector<SDValue, 8> V(NumElems);
6047   if (NumElems == 4 && NumZero > 0) {
6048     for (unsigned i = 0; i < 4; ++i) {
6049       bool isZero = !(NonZeros & (1 << i));
6050       if (isZero)
6051         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6052       else
6053         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6054     }
6055
6056     for (unsigned i = 0; i < 2; ++i) {
6057       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6058         default: break;
6059         case 0:
6060           V[i] = V[i*2];  // Must be a zero vector.
6061           break;
6062         case 1:
6063           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6064           break;
6065         case 2:
6066           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6067           break;
6068         case 3:
6069           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6070           break;
6071       }
6072     }
6073
6074     bool Reverse1 = (NonZeros & 0x3) == 2;
6075     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6076     int MaskVec[] = {
6077       Reverse1 ? 1 : 0,
6078       Reverse1 ? 0 : 1,
6079       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6080       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6081     };
6082     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6083   }
6084
6085   if (Values.size() > 1 && VT.is128BitVector()) {
6086     // Check for a build vector of consecutive loads.
6087     for (unsigned i = 0; i < NumElems; ++i)
6088       V[i] = Op.getOperand(i);
6089
6090     // Check for elements which are consecutive loads.
6091     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6092       return LD;
6093
6094     // Check for a build vector from mostly shuffle plus few inserting.
6095     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6096       return Sh;
6097
6098     // For SSE 4.1, use insertps to put the high elements into the low element.
6099     if (Subtarget->hasSSE41()) {
6100       SDValue Result;
6101       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6102         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6103       else
6104         Result = DAG.getUNDEF(VT);
6105
6106       for (unsigned i = 1; i < NumElems; ++i) {
6107         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6108         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6109                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6110       }
6111       return Result;
6112     }
6113
6114     // Otherwise, expand into a number of unpckl*, start by extending each of
6115     // our (non-undef) elements to the full vector width with the element in the
6116     // bottom slot of the vector (which generates no code for SSE).
6117     for (unsigned i = 0; i < NumElems; ++i) {
6118       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6119         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6120       else
6121         V[i] = DAG.getUNDEF(VT);
6122     }
6123
6124     // Next, we iteratively mix elements, e.g. for v4f32:
6125     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6126     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6127     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6128     unsigned EltStride = NumElems >> 1;
6129     while (EltStride != 0) {
6130       for (unsigned i = 0; i < EltStride; ++i) {
6131         // If V[i+EltStride] is undef and this is the first round of mixing,
6132         // then it is safe to just drop this shuffle: V[i] is already in the
6133         // right place, the one element (since it's the first round) being
6134         // inserted as undef can be dropped.  This isn't safe for successive
6135         // rounds because they will permute elements within both vectors.
6136         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6137             EltStride == NumElems/2)
6138           continue;
6139
6140         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6141       }
6142       EltStride >>= 1;
6143     }
6144     return V[0];
6145   }
6146   return SDValue();
6147 }
6148
6149 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6150 // to create 256-bit vectors from two other 128-bit ones.
6151 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6152   SDLoc dl(Op);
6153   MVT ResVT = Op.getSimpleValueType();
6154
6155   assert((ResVT.is256BitVector() ||
6156           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6157
6158   SDValue V1 = Op.getOperand(0);
6159   SDValue V2 = Op.getOperand(1);
6160   unsigned NumElems = ResVT.getVectorNumElements();
6161   if (ResVT.is256BitVector())
6162     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6163
6164   if (Op.getNumOperands() == 4) {
6165     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6166                                 ResVT.getVectorNumElements()/2);
6167     SDValue V3 = Op.getOperand(2);
6168     SDValue V4 = Op.getOperand(3);
6169     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6170       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6171   }
6172   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6173 }
6174
6175 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6176                                        const X86Subtarget *Subtarget,
6177                                        SelectionDAG & DAG) {
6178   SDLoc dl(Op);
6179   MVT ResVT = Op.getSimpleValueType();
6180   unsigned NumOfOperands = Op.getNumOperands();
6181
6182   assert(isPowerOf2_32(NumOfOperands) &&
6183          "Unexpected number of operands in CONCAT_VECTORS");
6184
6185   if (NumOfOperands > 2) {
6186     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6187                                   ResVT.getVectorNumElements()/2);
6188     SmallVector<SDValue, 2> Ops;
6189     for (unsigned i = 0; i < NumOfOperands/2; i++)
6190       Ops.push_back(Op.getOperand(i));
6191     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6192     Ops.clear();
6193     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6194       Ops.push_back(Op.getOperand(i));
6195     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6196     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6197   }
6198
6199   SDValue V1 = Op.getOperand(0);
6200   SDValue V2 = Op.getOperand(1);
6201   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6202   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6203
6204   if (IsZeroV1 && IsZeroV2)
6205     return getZeroVector(ResVT, Subtarget, DAG, dl);
6206
6207   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6208   SDValue Undef = DAG.getUNDEF(ResVT);
6209   unsigned NumElems = ResVT.getVectorNumElements();
6210   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6211
6212   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6213   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6214   if (IsZeroV1)
6215     return V2;
6216
6217   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6218   // Zero the upper bits of V1
6219   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6220   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6221   if (IsZeroV2)
6222     return V1;
6223   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6224 }
6225
6226 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6227                                    const X86Subtarget *Subtarget,
6228                                    SelectionDAG &DAG) {
6229   MVT VT = Op.getSimpleValueType();
6230   if (VT.getVectorElementType() == MVT::i1)
6231     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6232
6233   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6234          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6235           Op.getNumOperands() == 4)));
6236
6237   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6238   // from two other 128-bit ones.
6239
6240   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6241   return LowerAVXCONCAT_VECTORS(Op, DAG);
6242 }
6243
6244
6245 //===----------------------------------------------------------------------===//
6246 // Vector shuffle lowering
6247 //
6248 // This is an experimental code path for lowering vector shuffles on x86. It is
6249 // designed to handle arbitrary vector shuffles and blends, gracefully
6250 // degrading performance as necessary. It works hard to recognize idiomatic
6251 // shuffles and lower them to optimal instruction patterns without leaving
6252 // a framework that allows reasonably efficient handling of all vector shuffle
6253 // patterns.
6254 //===----------------------------------------------------------------------===//
6255
6256 /// \brief Tiny helper function to identify a no-op mask.
6257 ///
6258 /// This is a somewhat boring predicate function. It checks whether the mask
6259 /// array input, which is assumed to be a single-input shuffle mask of the kind
6260 /// used by the X86 shuffle instructions (not a fully general
6261 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6262 /// in-place shuffle are 'no-op's.
6263 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6264   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6265     if (Mask[i] != -1 && Mask[i] != i)
6266       return false;
6267   return true;
6268 }
6269
6270 /// \brief Helper function to classify a mask as a single-input mask.
6271 ///
6272 /// This isn't a generic single-input test because in the vector shuffle
6273 /// lowering we canonicalize single inputs to be the first input operand. This
6274 /// means we can more quickly test for a single input by only checking whether
6275 /// an input from the second operand exists. We also assume that the size of
6276 /// mask corresponds to the size of the input vectors which isn't true in the
6277 /// fully general case.
6278 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6279   for (int M : Mask)
6280     if (M >= (int)Mask.size())
6281       return false;
6282   return true;
6283 }
6284
6285 /// \brief Test whether there are elements crossing 128-bit lanes in this
6286 /// shuffle mask.
6287 ///
6288 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6289 /// and we routinely test for these.
6290 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6291   int LaneSize = 128 / VT.getScalarSizeInBits();
6292   int Size = Mask.size();
6293   for (int i = 0; i < Size; ++i)
6294     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6295       return true;
6296   return false;
6297 }
6298
6299 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6300 ///
6301 /// This checks a shuffle mask to see if it is performing the same
6302 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6303 /// that it is also not lane-crossing. It may however involve a blend from the
6304 /// same lane of a second vector.
6305 ///
6306 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6307 /// non-trivial to compute in the face of undef lanes. The representation is
6308 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6309 /// entries from both V1 and V2 inputs to the wider mask.
6310 static bool
6311 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6312                                 SmallVectorImpl<int> &RepeatedMask) {
6313   int LaneSize = 128 / VT.getScalarSizeInBits();
6314   RepeatedMask.resize(LaneSize, -1);
6315   int Size = Mask.size();
6316   for (int i = 0; i < Size; ++i) {
6317     if (Mask[i] < 0)
6318       continue;
6319     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6320       // This entry crosses lanes, so there is no way to model this shuffle.
6321       return false;
6322
6323     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6324     if (RepeatedMask[i % LaneSize] == -1)
6325       // This is the first non-undef entry in this slot of a 128-bit lane.
6326       RepeatedMask[i % LaneSize] =
6327           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6328     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6329       // Found a mismatch with the repeated mask.
6330       return false;
6331   }
6332   return true;
6333 }
6334
6335 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6336 /// arguments.
6337 ///
6338 /// This is a fast way to test a shuffle mask against a fixed pattern:
6339 ///
6340 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6341 ///
6342 /// It returns true if the mask is exactly as wide as the argument list, and
6343 /// each element of the mask is either -1 (signifying undef) or the value given
6344 /// in the argument.
6345 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6346                                 ArrayRef<int> ExpectedMask) {
6347   if (Mask.size() != ExpectedMask.size())
6348     return false;
6349
6350   int Size = Mask.size();
6351
6352   // If the values are build vectors, we can look through them to find
6353   // equivalent inputs that make the shuffles equivalent.
6354   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6355   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6356
6357   for (int i = 0; i < Size; ++i)
6358     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6359       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6360       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6361       if (!MaskBV || !ExpectedBV ||
6362           MaskBV->getOperand(Mask[i] % Size) !=
6363               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6364         return false;
6365     }
6366
6367   return true;
6368 }
6369
6370 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6371 ///
6372 /// This helper function produces an 8-bit shuffle immediate corresponding to
6373 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6374 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6375 /// example.
6376 ///
6377 /// NB: We rely heavily on "undef" masks preserving the input lane.
6378 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6379                                           SelectionDAG &DAG) {
6380   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6381   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6382   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6383   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6384   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6385
6386   unsigned Imm = 0;
6387   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6388   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6389   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6390   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6391   return DAG.getConstant(Imm, DL, MVT::i8);
6392 }
6393
6394 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6395 ///
6396 /// This is used as a fallback approach when first class blend instructions are
6397 /// unavailable. Currently it is only suitable for integer vectors, but could
6398 /// be generalized for floating point vectors if desirable.
6399 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6400                                             SDValue V2, ArrayRef<int> Mask,
6401                                             SelectionDAG &DAG) {
6402   assert(VT.isInteger() && "Only supports integer vector types!");
6403   MVT EltVT = VT.getScalarType();
6404   int NumEltBits = EltVT.getSizeInBits();
6405   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6406   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6407                                     EltVT);
6408   SmallVector<SDValue, 16> MaskOps;
6409   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6410     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6411       return SDValue(); // Shuffled input!
6412     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6413   }
6414
6415   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6416   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6417   // We have to cast V2 around.
6418   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6419   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6420                                       DAG.getBitcast(MaskVT, V1Mask),
6421                                       DAG.getBitcast(MaskVT, V2)));
6422   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6423 }
6424
6425 /// \brief Try to emit a blend instruction for a shuffle.
6426 ///
6427 /// This doesn't do any checks for the availability of instructions for blending
6428 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6429 /// be matched in the backend with the type given. What it does check for is
6430 /// that the shuffle mask is in fact a blend.
6431 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6432                                          SDValue V2, ArrayRef<int> Mask,
6433                                          const X86Subtarget *Subtarget,
6434                                          SelectionDAG &DAG) {
6435   unsigned BlendMask = 0;
6436   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6437     if (Mask[i] >= Size) {
6438       if (Mask[i] != i + Size)
6439         return SDValue(); // Shuffled V2 input!
6440       BlendMask |= 1u << i;
6441       continue;
6442     }
6443     if (Mask[i] >= 0 && Mask[i] != i)
6444       return SDValue(); // Shuffled V1 input!
6445   }
6446   switch (VT.SimpleTy) {
6447   case MVT::v2f64:
6448   case MVT::v4f32:
6449   case MVT::v4f64:
6450   case MVT::v8f32:
6451     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6452                        DAG.getConstant(BlendMask, DL, MVT::i8));
6453
6454   case MVT::v4i64:
6455   case MVT::v8i32:
6456     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6457     // FALLTHROUGH
6458   case MVT::v2i64:
6459   case MVT::v4i32:
6460     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6461     // that instruction.
6462     if (Subtarget->hasAVX2()) {
6463       // Scale the blend by the number of 32-bit dwords per element.
6464       int Scale =  VT.getScalarSizeInBits() / 32;
6465       BlendMask = 0;
6466       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6467         if (Mask[i] >= Size)
6468           for (int j = 0; j < Scale; ++j)
6469             BlendMask |= 1u << (i * Scale + j);
6470
6471       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6472       V1 = DAG.getBitcast(BlendVT, V1);
6473       V2 = DAG.getBitcast(BlendVT, V2);
6474       return DAG.getBitcast(
6475           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6476                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6477     }
6478     // FALLTHROUGH
6479   case MVT::v8i16: {
6480     // For integer shuffles we need to expand the mask and cast the inputs to
6481     // v8i16s prior to blending.
6482     int Scale = 8 / VT.getVectorNumElements();
6483     BlendMask = 0;
6484     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6485       if (Mask[i] >= Size)
6486         for (int j = 0; j < Scale; ++j)
6487           BlendMask |= 1u << (i * Scale + j);
6488
6489     V1 = DAG.getBitcast(MVT::v8i16, V1);
6490     V2 = DAG.getBitcast(MVT::v8i16, V2);
6491     return DAG.getBitcast(VT,
6492                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6493                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6494   }
6495
6496   case MVT::v16i16: {
6497     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6498     SmallVector<int, 8> RepeatedMask;
6499     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6500       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6501       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6502       BlendMask = 0;
6503       for (int i = 0; i < 8; ++i)
6504         if (RepeatedMask[i] >= 16)
6505           BlendMask |= 1u << i;
6506       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6507                          DAG.getConstant(BlendMask, DL, MVT::i8));
6508     }
6509   }
6510     // FALLTHROUGH
6511   case MVT::v16i8:
6512   case MVT::v32i8: {
6513     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6514            "256-bit byte-blends require AVX2 support!");
6515
6516     // Scale the blend by the number of bytes per element.
6517     int Scale = VT.getScalarSizeInBits() / 8;
6518
6519     // This form of blend is always done on bytes. Compute the byte vector
6520     // type.
6521     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6522
6523     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6524     // mix of LLVM's code generator and the x86 backend. We tell the code
6525     // generator that boolean values in the elements of an x86 vector register
6526     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6527     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6528     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6529     // of the element (the remaining are ignored) and 0 in that high bit would
6530     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6531     // the LLVM model for boolean values in vector elements gets the relevant
6532     // bit set, it is set backwards and over constrained relative to x86's
6533     // actual model.
6534     SmallVector<SDValue, 32> VSELECTMask;
6535     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6536       for (int j = 0; j < Scale; ++j)
6537         VSELECTMask.push_back(
6538             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6539                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6540                                           MVT::i8));
6541
6542     V1 = DAG.getBitcast(BlendVT, V1);
6543     V2 = DAG.getBitcast(BlendVT, V2);
6544     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6545                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6546                                                       BlendVT, VSELECTMask),
6547                                           V1, V2));
6548   }
6549
6550   default:
6551     llvm_unreachable("Not a supported integer vector type!");
6552   }
6553 }
6554
6555 /// \brief Try to lower as a blend of elements from two inputs followed by
6556 /// a single-input permutation.
6557 ///
6558 /// This matches the pattern where we can blend elements from two inputs and
6559 /// then reduce the shuffle to a single-input permutation.
6560 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6561                                                    SDValue V2,
6562                                                    ArrayRef<int> Mask,
6563                                                    SelectionDAG &DAG) {
6564   // We build up the blend mask while checking whether a blend is a viable way
6565   // to reduce the shuffle.
6566   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6567   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6568
6569   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6570     if (Mask[i] < 0)
6571       continue;
6572
6573     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6574
6575     if (BlendMask[Mask[i] % Size] == -1)
6576       BlendMask[Mask[i] % Size] = Mask[i];
6577     else if (BlendMask[Mask[i] % Size] != Mask[i])
6578       return SDValue(); // Can't blend in the needed input!
6579
6580     PermuteMask[i] = Mask[i] % Size;
6581   }
6582
6583   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6584   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6585 }
6586
6587 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6588 /// blends and permutes.
6589 ///
6590 /// This matches the extremely common pattern for handling combined
6591 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6592 /// operations. It will try to pick the best arrangement of shuffles and
6593 /// blends.
6594 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6595                                                           SDValue V1,
6596                                                           SDValue V2,
6597                                                           ArrayRef<int> Mask,
6598                                                           SelectionDAG &DAG) {
6599   // Shuffle the input elements into the desired positions in V1 and V2 and
6600   // blend them together.
6601   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6602   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6603   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6604   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6605     if (Mask[i] >= 0 && Mask[i] < Size) {
6606       V1Mask[i] = Mask[i];
6607       BlendMask[i] = i;
6608     } else if (Mask[i] >= Size) {
6609       V2Mask[i] = Mask[i] - Size;
6610       BlendMask[i] = i + Size;
6611     }
6612
6613   // Try to lower with the simpler initial blend strategy unless one of the
6614   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6615   // shuffle may be able to fold with a load or other benefit. However, when
6616   // we'll have to do 2x as many shuffles in order to achieve this, blending
6617   // first is a better strategy.
6618   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6619     if (SDValue BlendPerm =
6620             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6621       return BlendPerm;
6622
6623   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6624   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6625   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6626 }
6627
6628 /// \brief Try to lower a vector shuffle as a byte rotation.
6629 ///
6630 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6631 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6632 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6633 /// try to generically lower a vector shuffle through such an pattern. It
6634 /// does not check for the profitability of lowering either as PALIGNR or
6635 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6636 /// This matches shuffle vectors that look like:
6637 ///
6638 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6639 ///
6640 /// Essentially it concatenates V1 and V2, shifts right by some number of
6641 /// elements, and takes the low elements as the result. Note that while this is
6642 /// specified as a *right shift* because x86 is little-endian, it is a *left
6643 /// rotate* of the vector lanes.
6644 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6645                                               SDValue V2,
6646                                               ArrayRef<int> Mask,
6647                                               const X86Subtarget *Subtarget,
6648                                               SelectionDAG &DAG) {
6649   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6650
6651   int NumElts = Mask.size();
6652   int NumLanes = VT.getSizeInBits() / 128;
6653   int NumLaneElts = NumElts / NumLanes;
6654
6655   // We need to detect various ways of spelling a rotation:
6656   //   [11, 12, 13, 14, 15,  0,  1,  2]
6657   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6658   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6659   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6660   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6661   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6662   int Rotation = 0;
6663   SDValue Lo, Hi;
6664   for (int l = 0; l < NumElts; l += NumLaneElts) {
6665     for (int i = 0; i < NumLaneElts; ++i) {
6666       if (Mask[l + i] == -1)
6667         continue;
6668       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6669
6670       // Get the mod-Size index and lane correct it.
6671       int LaneIdx = (Mask[l + i] % NumElts) - l;
6672       // Make sure it was in this lane.
6673       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6674         return SDValue();
6675
6676       // Determine where a rotated vector would have started.
6677       int StartIdx = i - LaneIdx;
6678       if (StartIdx == 0)
6679         // The identity rotation isn't interesting, stop.
6680         return SDValue();
6681
6682       // If we found the tail of a vector the rotation must be the missing
6683       // front. If we found the head of a vector, it must be how much of the
6684       // head.
6685       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6686
6687       if (Rotation == 0)
6688         Rotation = CandidateRotation;
6689       else if (Rotation != CandidateRotation)
6690         // The rotations don't match, so we can't match this mask.
6691         return SDValue();
6692
6693       // Compute which value this mask is pointing at.
6694       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6695
6696       // Compute which of the two target values this index should be assigned
6697       // to. This reflects whether the high elements are remaining or the low
6698       // elements are remaining.
6699       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6700
6701       // Either set up this value if we've not encountered it before, or check
6702       // that it remains consistent.
6703       if (!TargetV)
6704         TargetV = MaskV;
6705       else if (TargetV != MaskV)
6706         // This may be a rotation, but it pulls from the inputs in some
6707         // unsupported interleaving.
6708         return SDValue();
6709     }
6710   }
6711
6712   // Check that we successfully analyzed the mask, and normalize the results.
6713   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6714   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6715   if (!Lo)
6716     Lo = Hi;
6717   else if (!Hi)
6718     Hi = Lo;
6719
6720   // The actual rotate instruction rotates bytes, so we need to scale the
6721   // rotation based on how many bytes are in the vector lane.
6722   int Scale = 16 / NumLaneElts;
6723
6724   // SSSE3 targets can use the palignr instruction.
6725   if (Subtarget->hasSSSE3()) {
6726     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6727     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6728     Lo = DAG.getBitcast(AlignVT, Lo);
6729     Hi = DAG.getBitcast(AlignVT, Hi);
6730
6731     return DAG.getBitcast(
6732         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6733                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6734   }
6735
6736   assert(VT.getSizeInBits() == 128 &&
6737          "Rotate-based lowering only supports 128-bit lowering!");
6738   assert(Mask.size() <= 16 &&
6739          "Can shuffle at most 16 bytes in a 128-bit vector!");
6740
6741   // Default SSE2 implementation
6742   int LoByteShift = 16 - Rotation * Scale;
6743   int HiByteShift = Rotation * Scale;
6744
6745   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6746   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6747   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6748
6749   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6750                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6751   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6752                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6753   return DAG.getBitcast(VT,
6754                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6755 }
6756
6757 /// \brief Compute whether each element of a shuffle is zeroable.
6758 ///
6759 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6760 /// Either it is an undef element in the shuffle mask, the element of the input
6761 /// referenced is undef, or the element of the input referenced is known to be
6762 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6763 /// as many lanes with this technique as possible to simplify the remaining
6764 /// shuffle.
6765 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6766                                                      SDValue V1, SDValue V2) {
6767   SmallBitVector Zeroable(Mask.size(), false);
6768
6769   while (V1.getOpcode() == ISD::BITCAST)
6770     V1 = V1->getOperand(0);
6771   while (V2.getOpcode() == ISD::BITCAST)
6772     V2 = V2->getOperand(0);
6773
6774   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6775   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6776
6777   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6778     int M = Mask[i];
6779     // Handle the easy cases.
6780     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6781       Zeroable[i] = true;
6782       continue;
6783     }
6784
6785     // If this is an index into a build_vector node (which has the same number
6786     // of elements), dig out the input value and use it.
6787     SDValue V = M < Size ? V1 : V2;
6788     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6789       continue;
6790
6791     SDValue Input = V.getOperand(M % Size);
6792     // The UNDEF opcode check really should be dead code here, but not quite
6793     // worth asserting on (it isn't invalid, just unexpected).
6794     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6795       Zeroable[i] = true;
6796   }
6797
6798   return Zeroable;
6799 }
6800
6801 /// \brief Try to emit a bitmask instruction for a shuffle.
6802 ///
6803 /// This handles cases where we can model a blend exactly as a bitmask due to
6804 /// one of the inputs being zeroable.
6805 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6806                                            SDValue V2, ArrayRef<int> Mask,
6807                                            SelectionDAG &DAG) {
6808   MVT EltVT = VT.getScalarType();
6809   int NumEltBits = EltVT.getSizeInBits();
6810   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6811   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6812   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6813                                     IntEltVT);
6814   if (EltVT.isFloatingPoint()) {
6815     Zero = DAG.getBitcast(EltVT, Zero);
6816     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6817   }
6818   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6819   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6820   SDValue V;
6821   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6822     if (Zeroable[i])
6823       continue;
6824     if (Mask[i] % Size != i)
6825       return SDValue(); // Not a blend.
6826     if (!V)
6827       V = Mask[i] < Size ? V1 : V2;
6828     else if (V != (Mask[i] < Size ? V1 : V2))
6829       return SDValue(); // Can only let one input through the mask.
6830
6831     VMaskOps[i] = AllOnes;
6832   }
6833   if (!V)
6834     return SDValue(); // No non-zeroable elements!
6835
6836   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6837   V = DAG.getNode(VT.isFloatingPoint()
6838                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6839                   DL, VT, V, VMask);
6840   return V;
6841 }
6842
6843 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6844 ///
6845 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6846 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6847 /// matches elements from one of the input vectors shuffled to the left or
6848 /// right with zeroable elements 'shifted in'. It handles both the strictly
6849 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6850 /// quad word lane.
6851 ///
6852 /// PSHL : (little-endian) left bit shift.
6853 /// [ zz, 0, zz,  2 ]
6854 /// [ -1, 4, zz, -1 ]
6855 /// PSRL : (little-endian) right bit shift.
6856 /// [  1, zz,  3, zz]
6857 /// [ -1, -1,  7, zz]
6858 /// PSLLDQ : (little-endian) left byte shift
6859 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6860 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6861 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6862 /// PSRLDQ : (little-endian) right byte shift
6863 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6864 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6865 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6866 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6867                                          SDValue V2, ArrayRef<int> Mask,
6868                                          SelectionDAG &DAG) {
6869   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6870
6871   int Size = Mask.size();
6872   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6873
6874   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6875     for (int i = 0; i < Size; i += Scale)
6876       for (int j = 0; j < Shift; ++j)
6877         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6878           return false;
6879
6880     return true;
6881   };
6882
6883   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6884     for (int i = 0; i != Size; i += Scale) {
6885       unsigned Pos = Left ? i + Shift : i;
6886       unsigned Low = Left ? i : i + Shift;
6887       unsigned Len = Scale - Shift;
6888       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6889                                       Low + (V == V1 ? 0 : Size)))
6890         return SDValue();
6891     }
6892
6893     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6894     bool ByteShift = ShiftEltBits > 64;
6895     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6896                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6897     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6898
6899     // Normalize the scale for byte shifts to still produce an i64 element
6900     // type.
6901     Scale = ByteShift ? Scale / 2 : Scale;
6902
6903     // We need to round trip through the appropriate type for the shift.
6904     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6905     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6906     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6907            "Illegal integer vector type");
6908     V = DAG.getBitcast(ShiftVT, V);
6909
6910     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6911                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6912     return DAG.getBitcast(VT, V);
6913   };
6914
6915   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6916   // keep doubling the size of the integer elements up to that. We can
6917   // then shift the elements of the integer vector by whole multiples of
6918   // their width within the elements of the larger integer vector. Test each
6919   // multiple to see if we can find a match with the moved element indices
6920   // and that the shifted in elements are all zeroable.
6921   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6922     for (int Shift = 1; Shift != Scale; ++Shift)
6923       for (bool Left : {true, false})
6924         if (CheckZeros(Shift, Scale, Left))
6925           for (SDValue V : {V1, V2})
6926             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6927               return Match;
6928
6929   // no match
6930   return SDValue();
6931 }
6932
6933 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6934 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6935                                            SDValue V2, ArrayRef<int> Mask,
6936                                            SelectionDAG &DAG) {
6937   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6938   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6939
6940   int Size = Mask.size();
6941   int HalfSize = Size / 2;
6942   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6943
6944   // Upper half must be undefined.
6945   if (!isUndefInRange(Mask, HalfSize, HalfSize))
6946     return SDValue();
6947
6948   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
6949   // Remainder of lower half result is zero and upper half is all undef.
6950   auto LowerAsEXTRQ = [&]() {
6951     // Determine the extraction length from the part of the
6952     // lower half that isn't zeroable.
6953     int Len = HalfSize;
6954     for (; Len >= 0; --Len)
6955       if (!Zeroable[Len - 1])
6956         break;
6957     assert(Len > 0 && "Zeroable shuffle mask");
6958
6959     // Attempt to match first Len sequential elements from the lower half.
6960     SDValue Src;
6961     int Idx = -1;
6962     for (int i = 0; i != Len; ++i) {
6963       int M = Mask[i];
6964       if (M < 0)
6965         continue;
6966       SDValue &V = (M < Size ? V1 : V2);
6967       M = M % Size;
6968
6969       // All mask elements must be in the lower half.
6970       if (M > HalfSize)
6971         return SDValue();
6972
6973       if (Idx < 0 || (Src == V && Idx == (M - i))) {
6974         Src = V;
6975         Idx = M - i;
6976         continue;
6977       }
6978       return SDValue();
6979     }
6980
6981     if (Idx < 0)
6982       return SDValue();
6983
6984     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
6985     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
6986     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
6987     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
6988                        DAG.getConstant(BitLen, DL, MVT::i8),
6989                        DAG.getConstant(BitIdx, DL, MVT::i8));
6990   };
6991
6992   if (SDValue ExtrQ = LowerAsEXTRQ())
6993     return ExtrQ;
6994
6995   // INSERTQ: Extract lowest Len elements from lower half of second source and
6996   // insert over first source, starting at Idx.
6997   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
6998   auto LowerAsInsertQ = [&]() {
6999     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7000       SDValue Base;
7001
7002       // Attempt to match first source from mask before insertion point.
7003       if (isUndefInRange(Mask, 0, Idx)) {
7004         /* EMPTY */
7005       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7006         Base = V1;
7007       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7008         Base = V2;
7009       } else {
7010         continue;
7011       }
7012
7013       // Extend the extraction length looking to match both the insertion of
7014       // the second source and the remaining elements of the first.
7015       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7016         SDValue Insert;
7017         int Len = Hi - Idx;
7018
7019         // Match insertion.
7020         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7021           Insert = V1;
7022         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7023           Insert = V2;
7024         } else {
7025           continue;
7026         }
7027
7028         // Match the remaining elements of the lower half.
7029         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7030           /* EMPTY */
7031         } else if ((!Base || (Base == V1)) &&
7032                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7033           Base = V1;
7034         } else if ((!Base || (Base == V2)) &&
7035                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7036                                               Size + Hi)) {
7037           Base = V2;
7038         } else {
7039           continue;
7040         }
7041
7042         // We may not have a base (first source) - this can safely be undefined.
7043         if (!Base)
7044           Base = DAG.getUNDEF(VT);
7045
7046         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7047         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7048         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7049                            DAG.getConstant(BitLen, DL, MVT::i8),
7050                            DAG.getConstant(BitIdx, DL, MVT::i8));
7051       }
7052     }
7053
7054     return SDValue();
7055   };
7056
7057   if (SDValue InsertQ = LowerAsInsertQ())
7058     return InsertQ;
7059
7060   return SDValue();
7061 }
7062
7063 /// \brief Lower a vector shuffle as a zero or any extension.
7064 ///
7065 /// Given a specific number of elements, element bit width, and extension
7066 /// stride, produce either a zero or any extension based on the available
7067 /// features of the subtarget.
7068 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7069     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7070     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7071   assert(Scale > 1 && "Need a scale to extend.");
7072   int NumElements = VT.getVectorNumElements();
7073   int EltBits = VT.getScalarSizeInBits();
7074   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7075          "Only 8, 16, and 32 bit elements can be extended.");
7076   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7077
7078   // Found a valid zext mask! Try various lowering strategies based on the
7079   // input type and available ISA extensions.
7080   if (Subtarget->hasSSE41()) {
7081     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7082                                  NumElements / Scale);
7083     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7084   }
7085
7086   // For any extends we can cheat for larger element sizes and use shuffle
7087   // instructions that can fold with a load and/or copy.
7088   if (AnyExt && EltBits == 32) {
7089     int PSHUFDMask[4] = {0, -1, 1, -1};
7090     return DAG.getBitcast(
7091         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7092                         DAG.getBitcast(MVT::v4i32, InputV),
7093                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7094   }
7095   if (AnyExt && EltBits == 16 && Scale > 2) {
7096     int PSHUFDMask[4] = {0, -1, 0, -1};
7097     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7098                          DAG.getBitcast(MVT::v4i32, InputV),
7099                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7100     int PSHUFHWMask[4] = {1, -1, -1, -1};
7101     return DAG.getBitcast(
7102         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7103                         DAG.getBitcast(MVT::v8i16, InputV),
7104                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7105   }
7106
7107   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7108   // to 64-bits.
7109   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7110     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7111     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7112
7113     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7114                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7115                                          DAG.getConstant(EltBits, DL, MVT::i8),
7116                                          DAG.getConstant(0, DL, MVT::i8)));
7117     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7118       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7119
7120     SDValue Hi =
7121         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7122                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7123                                 DAG.getConstant(EltBits, DL, MVT::i8),
7124                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7125     return DAG.getNode(ISD::BITCAST, DL, VT,
7126                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7127   }
7128
7129   // If this would require more than 2 unpack instructions to expand, use
7130   // pshufb when available. We can only use more than 2 unpack instructions
7131   // when zero extending i8 elements which also makes it easier to use pshufb.
7132   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7133     assert(NumElements == 16 && "Unexpected byte vector width!");
7134     SDValue PSHUFBMask[16];
7135     for (int i = 0; i < 16; ++i)
7136       PSHUFBMask[i] =
7137           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7138     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7139     return DAG.getBitcast(VT,
7140                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7141                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7142                                                   MVT::v16i8, PSHUFBMask)));
7143   }
7144
7145   // Otherwise emit a sequence of unpacks.
7146   do {
7147     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7148     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7149                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7150     InputV = DAG.getBitcast(InputVT, InputV);
7151     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7152     Scale /= 2;
7153     EltBits *= 2;
7154     NumElements /= 2;
7155   } while (Scale > 1);
7156   return DAG.getBitcast(VT, InputV);
7157 }
7158
7159 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7160 ///
7161 /// This routine will try to do everything in its power to cleverly lower
7162 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7163 /// check for the profitability of this lowering,  it tries to aggressively
7164 /// match this pattern. It will use all of the micro-architectural details it
7165 /// can to emit an efficient lowering. It handles both blends with all-zero
7166 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7167 /// masking out later).
7168 ///
7169 /// The reason we have dedicated lowering for zext-style shuffles is that they
7170 /// are both incredibly common and often quite performance sensitive.
7171 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7172     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7173     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7174   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7175
7176   int Bits = VT.getSizeInBits();
7177   int NumElements = VT.getVectorNumElements();
7178   assert(VT.getScalarSizeInBits() <= 32 &&
7179          "Exceeds 32-bit integer zero extension limit");
7180   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7181
7182   // Define a helper function to check a particular ext-scale and lower to it if
7183   // valid.
7184   auto Lower = [&](int Scale) -> SDValue {
7185     SDValue InputV;
7186     bool AnyExt = true;
7187     for (int i = 0; i < NumElements; ++i) {
7188       if (Mask[i] == -1)
7189         continue; // Valid anywhere but doesn't tell us anything.
7190       if (i % Scale != 0) {
7191         // Each of the extended elements need to be zeroable.
7192         if (!Zeroable[i])
7193           return SDValue();
7194
7195         // We no longer are in the anyext case.
7196         AnyExt = false;
7197         continue;
7198       }
7199
7200       // Each of the base elements needs to be consecutive indices into the
7201       // same input vector.
7202       SDValue V = Mask[i] < NumElements ? V1 : V2;
7203       if (!InputV)
7204         InputV = V;
7205       else if (InputV != V)
7206         return SDValue(); // Flip-flopping inputs.
7207
7208       if (Mask[i] % NumElements != i / Scale)
7209         return SDValue(); // Non-consecutive strided elements.
7210     }
7211
7212     // If we fail to find an input, we have a zero-shuffle which should always
7213     // have already been handled.
7214     // FIXME: Maybe handle this here in case during blending we end up with one?
7215     if (!InputV)
7216       return SDValue();
7217
7218     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7219         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7220   };
7221
7222   // The widest scale possible for extending is to a 64-bit integer.
7223   assert(Bits % 64 == 0 &&
7224          "The number of bits in a vector must be divisible by 64 on x86!");
7225   int NumExtElements = Bits / 64;
7226
7227   // Each iteration, try extending the elements half as much, but into twice as
7228   // many elements.
7229   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7230     assert(NumElements % NumExtElements == 0 &&
7231            "The input vector size must be divisible by the extended size.");
7232     if (SDValue V = Lower(NumElements / NumExtElements))
7233       return V;
7234   }
7235
7236   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7237   if (Bits != 128)
7238     return SDValue();
7239
7240   // Returns one of the source operands if the shuffle can be reduced to a
7241   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7242   auto CanZExtLowHalf = [&]() {
7243     for (int i = NumElements / 2; i != NumElements; ++i)
7244       if (!Zeroable[i])
7245         return SDValue();
7246     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7247       return V1;
7248     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7249       return V2;
7250     return SDValue();
7251   };
7252
7253   if (SDValue V = CanZExtLowHalf()) {
7254     V = DAG.getBitcast(MVT::v2i64, V);
7255     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7256     return DAG.getBitcast(VT, V);
7257   }
7258
7259   // No viable ext lowering found.
7260   return SDValue();
7261 }
7262
7263 /// \brief Try to get a scalar value for a specific element of a vector.
7264 ///
7265 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7266 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7267                                               SelectionDAG &DAG) {
7268   MVT VT = V.getSimpleValueType();
7269   MVT EltVT = VT.getVectorElementType();
7270   while (V.getOpcode() == ISD::BITCAST)
7271     V = V.getOperand(0);
7272   // If the bitcasts shift the element size, we can't extract an equivalent
7273   // element from it.
7274   MVT NewVT = V.getSimpleValueType();
7275   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7276     return SDValue();
7277
7278   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7279       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7280     // Ensure the scalar operand is the same size as the destination.
7281     // FIXME: Add support for scalar truncation where possible.
7282     SDValue S = V.getOperand(Idx);
7283     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7284       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7285   }
7286
7287   return SDValue();
7288 }
7289
7290 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7291 ///
7292 /// This is particularly important because the set of instructions varies
7293 /// significantly based on whether the operand is a load or not.
7294 static bool isShuffleFoldableLoad(SDValue V) {
7295   while (V.getOpcode() == ISD::BITCAST)
7296     V = V.getOperand(0);
7297
7298   return ISD::isNON_EXTLoad(V.getNode());
7299 }
7300
7301 /// \brief Try to lower insertion of a single element into a zero vector.
7302 ///
7303 /// This is a common pattern that we have especially efficient patterns to lower
7304 /// across all subtarget feature sets.
7305 static SDValue lowerVectorShuffleAsElementInsertion(
7306     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7307     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7308   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7309   MVT ExtVT = VT;
7310   MVT EltVT = VT.getVectorElementType();
7311
7312   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7313                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7314                 Mask.begin();
7315   bool IsV1Zeroable = true;
7316   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7317     if (i != V2Index && !Zeroable[i]) {
7318       IsV1Zeroable = false;
7319       break;
7320     }
7321
7322   // Check for a single input from a SCALAR_TO_VECTOR node.
7323   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7324   // all the smarts here sunk into that routine. However, the current
7325   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7326   // vector shuffle lowering is dead.
7327   if (SDValue V2S = getScalarValueForVectorElement(
7328           V2, Mask[V2Index] - Mask.size(), DAG)) {
7329     // We need to zext the scalar if it is smaller than an i32.
7330     V2S = DAG.getBitcast(EltVT, V2S);
7331     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7332       // Using zext to expand a narrow element won't work for non-zero
7333       // insertions.
7334       if (!IsV1Zeroable)
7335         return SDValue();
7336
7337       // Zero-extend directly to i32.
7338       ExtVT = MVT::v4i32;
7339       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7340     }
7341     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7342   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7343              EltVT == MVT::i16) {
7344     // Either not inserting from the low element of the input or the input
7345     // element size is too small to use VZEXT_MOVL to clear the high bits.
7346     return SDValue();
7347   }
7348
7349   if (!IsV1Zeroable) {
7350     // If V1 can't be treated as a zero vector we have fewer options to lower
7351     // this. We can't support integer vectors or non-zero targets cheaply, and
7352     // the V1 elements can't be permuted in any way.
7353     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7354     if (!VT.isFloatingPoint() || V2Index != 0)
7355       return SDValue();
7356     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7357     V1Mask[V2Index] = -1;
7358     if (!isNoopShuffleMask(V1Mask))
7359       return SDValue();
7360     // This is essentially a special case blend operation, but if we have
7361     // general purpose blend operations, they are always faster. Bail and let
7362     // the rest of the lowering handle these as blends.
7363     if (Subtarget->hasSSE41())
7364       return SDValue();
7365
7366     // Otherwise, use MOVSD or MOVSS.
7367     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7368            "Only two types of floating point element types to handle!");
7369     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7370                        ExtVT, V1, V2);
7371   }
7372
7373   // This lowering only works for the low element with floating point vectors.
7374   if (VT.isFloatingPoint() && V2Index != 0)
7375     return SDValue();
7376
7377   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7378   if (ExtVT != VT)
7379     V2 = DAG.getBitcast(VT, V2);
7380
7381   if (V2Index != 0) {
7382     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7383     // the desired position. Otherwise it is more efficient to do a vector
7384     // shift left. We know that we can do a vector shift left because all
7385     // the inputs are zero.
7386     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7387       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7388       V2Shuffle[V2Index] = 0;
7389       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7390     } else {
7391       V2 = DAG.getBitcast(MVT::v2i64, V2);
7392       V2 = DAG.getNode(
7393           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7394           DAG.getConstant(
7395               V2Index * EltVT.getSizeInBits()/8, DL,
7396               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7397       V2 = DAG.getBitcast(VT, V2);
7398     }
7399   }
7400   return V2;
7401 }
7402
7403 /// \brief Try to lower broadcast of a single element.
7404 ///
7405 /// For convenience, this code also bundles all of the subtarget feature set
7406 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7407 /// a convenient way to factor it out.
7408 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7409                                              ArrayRef<int> Mask,
7410                                              const X86Subtarget *Subtarget,
7411                                              SelectionDAG &DAG) {
7412   if (!Subtarget->hasAVX())
7413     return SDValue();
7414   if (VT.isInteger() && !Subtarget->hasAVX2())
7415     return SDValue();
7416
7417   // Check that the mask is a broadcast.
7418   int BroadcastIdx = -1;
7419   for (int M : Mask)
7420     if (M >= 0 && BroadcastIdx == -1)
7421       BroadcastIdx = M;
7422     else if (M >= 0 && M != BroadcastIdx)
7423       return SDValue();
7424
7425   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7426                                             "a sorted mask where the broadcast "
7427                                             "comes from V1.");
7428
7429   // Go up the chain of (vector) values to find a scalar load that we can
7430   // combine with the broadcast.
7431   for (;;) {
7432     switch (V.getOpcode()) {
7433     case ISD::CONCAT_VECTORS: {
7434       int OperandSize = Mask.size() / V.getNumOperands();
7435       V = V.getOperand(BroadcastIdx / OperandSize);
7436       BroadcastIdx %= OperandSize;
7437       continue;
7438     }
7439
7440     case ISD::INSERT_SUBVECTOR: {
7441       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7442       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7443       if (!ConstantIdx)
7444         break;
7445
7446       int BeginIdx = (int)ConstantIdx->getZExtValue();
7447       int EndIdx =
7448           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7449       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7450         BroadcastIdx -= BeginIdx;
7451         V = VInner;
7452       } else {
7453         V = VOuter;
7454       }
7455       continue;
7456     }
7457     }
7458     break;
7459   }
7460
7461   // Check if this is a broadcast of a scalar. We special case lowering
7462   // for scalars so that we can more effectively fold with loads.
7463   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7464       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7465     V = V.getOperand(BroadcastIdx);
7466
7467     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7468     // Only AVX2 has register broadcasts.
7469     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7470       return SDValue();
7471   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7472     // We can't broadcast from a vector register without AVX2, and we can only
7473     // broadcast from the zero-element of a vector register.
7474     return SDValue();
7475   }
7476
7477   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7478 }
7479
7480 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7481 // INSERTPS when the V1 elements are already in the correct locations
7482 // because otherwise we can just always use two SHUFPS instructions which
7483 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7484 // perform INSERTPS if a single V1 element is out of place and all V2
7485 // elements are zeroable.
7486 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7487                                             ArrayRef<int> Mask,
7488                                             SelectionDAG &DAG) {
7489   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7490   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7491   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7492   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7493
7494   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7495
7496   unsigned ZMask = 0;
7497   int V1DstIndex = -1;
7498   int V2DstIndex = -1;
7499   bool V1UsedInPlace = false;
7500
7501   for (int i = 0; i < 4; ++i) {
7502     // Synthesize a zero mask from the zeroable elements (includes undefs).
7503     if (Zeroable[i]) {
7504       ZMask |= 1 << i;
7505       continue;
7506     }
7507
7508     // Flag if we use any V1 inputs in place.
7509     if (i == Mask[i]) {
7510       V1UsedInPlace = true;
7511       continue;
7512     }
7513
7514     // We can only insert a single non-zeroable element.
7515     if (V1DstIndex != -1 || V2DstIndex != -1)
7516       return SDValue();
7517
7518     if (Mask[i] < 4) {
7519       // V1 input out of place for insertion.
7520       V1DstIndex = i;
7521     } else {
7522       // V2 input for insertion.
7523       V2DstIndex = i;
7524     }
7525   }
7526
7527   // Don't bother if we have no (non-zeroable) element for insertion.
7528   if (V1DstIndex == -1 && V2DstIndex == -1)
7529     return SDValue();
7530
7531   // Determine element insertion src/dst indices. The src index is from the
7532   // start of the inserted vector, not the start of the concatenated vector.
7533   unsigned V2SrcIndex = 0;
7534   if (V1DstIndex != -1) {
7535     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7536     // and don't use the original V2 at all.
7537     V2SrcIndex = Mask[V1DstIndex];
7538     V2DstIndex = V1DstIndex;
7539     V2 = V1;
7540   } else {
7541     V2SrcIndex = Mask[V2DstIndex] - 4;
7542   }
7543
7544   // If no V1 inputs are used in place, then the result is created only from
7545   // the zero mask and the V2 insertion - so remove V1 dependency.
7546   if (!V1UsedInPlace)
7547     V1 = DAG.getUNDEF(MVT::v4f32);
7548
7549   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7550   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7551
7552   // Insert the V2 element into the desired position.
7553   SDLoc DL(Op);
7554   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7555                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7556 }
7557
7558 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7559 /// UNPCK instruction.
7560 ///
7561 /// This specifically targets cases where we end up with alternating between
7562 /// the two inputs, and so can permute them into something that feeds a single
7563 /// UNPCK instruction. Note that this routine only targets integer vectors
7564 /// because for floating point vectors we have a generalized SHUFPS lowering
7565 /// strategy that handles everything that doesn't *exactly* match an unpack,
7566 /// making this clever lowering unnecessary.
7567 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7568                                           SDValue V2, ArrayRef<int> Mask,
7569                                           SelectionDAG &DAG) {
7570   assert(!VT.isFloatingPoint() &&
7571          "This routine only supports integer vectors.");
7572   assert(!isSingleInputShuffleMask(Mask) &&
7573          "This routine should only be used when blending two inputs.");
7574   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7575
7576   int Size = Mask.size();
7577
7578   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7579     return M >= 0 && M % Size < Size / 2;
7580   });
7581   int NumHiInputs = std::count_if(
7582       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7583
7584   bool UnpackLo = NumLoInputs >= NumHiInputs;
7585
7586   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7587     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7588     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7589
7590     for (int i = 0; i < Size; ++i) {
7591       if (Mask[i] < 0)
7592         continue;
7593
7594       // Each element of the unpack contains Scale elements from this mask.
7595       int UnpackIdx = i / Scale;
7596
7597       // We only handle the case where V1 feeds the first slots of the unpack.
7598       // We rely on canonicalization to ensure this is the case.
7599       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7600         return SDValue();
7601
7602       // Setup the mask for this input. The indexing is tricky as we have to
7603       // handle the unpack stride.
7604       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7605       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7606           Mask[i] % Size;
7607     }
7608
7609     // If we will have to shuffle both inputs to use the unpack, check whether
7610     // we can just unpack first and shuffle the result. If so, skip this unpack.
7611     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7612         !isNoopShuffleMask(V2Mask))
7613       return SDValue();
7614
7615     // Shuffle the inputs into place.
7616     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7617     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7618
7619     // Cast the inputs to the type we will use to unpack them.
7620     V1 = DAG.getBitcast(UnpackVT, V1);
7621     V2 = DAG.getBitcast(UnpackVT, V2);
7622
7623     // Unpack the inputs and cast the result back to the desired type.
7624     return DAG.getBitcast(
7625         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7626                         UnpackVT, V1, V2));
7627   };
7628
7629   // We try each unpack from the largest to the smallest to try and find one
7630   // that fits this mask.
7631   int OrigNumElements = VT.getVectorNumElements();
7632   int OrigScalarSize = VT.getScalarSizeInBits();
7633   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7634     int Scale = ScalarSize / OrigScalarSize;
7635     int NumElements = OrigNumElements / Scale;
7636     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7637     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7638       return Unpack;
7639   }
7640
7641   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7642   // initial unpack.
7643   if (NumLoInputs == 0 || NumHiInputs == 0) {
7644     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7645            "We have to have *some* inputs!");
7646     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7647
7648     // FIXME: We could consider the total complexity of the permute of each
7649     // possible unpacking. Or at the least we should consider how many
7650     // half-crossings are created.
7651     // FIXME: We could consider commuting the unpacks.
7652
7653     SmallVector<int, 32> PermMask;
7654     PermMask.assign(Size, -1);
7655     for (int i = 0; i < Size; ++i) {
7656       if (Mask[i] < 0)
7657         continue;
7658
7659       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7660
7661       PermMask[i] =
7662           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7663     }
7664     return DAG.getVectorShuffle(
7665         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7666                             DL, VT, V1, V2),
7667         DAG.getUNDEF(VT), PermMask);
7668   }
7669
7670   return SDValue();
7671 }
7672
7673 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7674 ///
7675 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7676 /// support for floating point shuffles but not integer shuffles. These
7677 /// instructions will incur a domain crossing penalty on some chips though so
7678 /// it is better to avoid lowering through this for integer vectors where
7679 /// possible.
7680 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7681                                        const X86Subtarget *Subtarget,
7682                                        SelectionDAG &DAG) {
7683   SDLoc DL(Op);
7684   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7685   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7686   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7687   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7688   ArrayRef<int> Mask = SVOp->getMask();
7689   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7690
7691   if (isSingleInputShuffleMask(Mask)) {
7692     // Use low duplicate instructions for masks that match their pattern.
7693     if (Subtarget->hasSSE3())
7694       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7695         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7696
7697     // Straight shuffle of a single input vector. Simulate this by using the
7698     // single input as both of the "inputs" to this instruction..
7699     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7700
7701     if (Subtarget->hasAVX()) {
7702       // If we have AVX, we can use VPERMILPS which will allow folding a load
7703       // into the shuffle.
7704       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7705                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7706     }
7707
7708     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7709                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7710   }
7711   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7712   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7713
7714   // If we have a single input, insert that into V1 if we can do so cheaply.
7715   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7716     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7717             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7718       return Insertion;
7719     // Try inverting the insertion since for v2 masks it is easy to do and we
7720     // can't reliably sort the mask one way or the other.
7721     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7722                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7723     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7724             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7725       return Insertion;
7726   }
7727
7728   // Try to use one of the special instruction patterns to handle two common
7729   // blend patterns if a zero-blend above didn't work.
7730   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7731       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7732     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7733       // We can either use a special instruction to load over the low double or
7734       // to move just the low double.
7735       return DAG.getNode(
7736           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7737           DL, MVT::v2f64, V2,
7738           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7739
7740   if (Subtarget->hasSSE41())
7741     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7742                                                   Subtarget, DAG))
7743       return Blend;
7744
7745   // Use dedicated unpack instructions for masks that match their pattern.
7746   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7747     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7748   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7749     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7750
7751   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7752   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7753                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7754 }
7755
7756 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7757 ///
7758 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7759 /// the integer unit to minimize domain crossing penalties. However, for blends
7760 /// it falls back to the floating point shuffle operation with appropriate bit
7761 /// casting.
7762 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7763                                        const X86Subtarget *Subtarget,
7764                                        SelectionDAG &DAG) {
7765   SDLoc DL(Op);
7766   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7767   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7768   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7769   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7770   ArrayRef<int> Mask = SVOp->getMask();
7771   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7772
7773   if (isSingleInputShuffleMask(Mask)) {
7774     // Check for being able to broadcast a single element.
7775     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7776                                                           Mask, Subtarget, DAG))
7777       return Broadcast;
7778
7779     // Straight shuffle of a single input vector. For everything from SSE2
7780     // onward this has a single fast instruction with no scary immediates.
7781     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7782     V1 = DAG.getBitcast(MVT::v4i32, V1);
7783     int WidenedMask[4] = {
7784         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7785         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7786     return DAG.getBitcast(
7787         MVT::v2i64,
7788         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7789                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7790   }
7791   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7792   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7793   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7794   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7795
7796   // If we have a blend of two PACKUS operations an the blend aligns with the
7797   // low and half halves, we can just merge the PACKUS operations. This is
7798   // particularly important as it lets us merge shuffles that this routine itself
7799   // creates.
7800   auto GetPackNode = [](SDValue V) {
7801     while (V.getOpcode() == ISD::BITCAST)
7802       V = V.getOperand(0);
7803
7804     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7805   };
7806   if (SDValue V1Pack = GetPackNode(V1))
7807     if (SDValue V2Pack = GetPackNode(V2))
7808       return DAG.getBitcast(MVT::v2i64,
7809                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7810                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7811                                                      : V1Pack.getOperand(1),
7812                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7813                                                      : V2Pack.getOperand(1)));
7814
7815   // Try to use shift instructions.
7816   if (SDValue Shift =
7817           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7818     return Shift;
7819
7820   // When loading a scalar and then shuffling it into a vector we can often do
7821   // the insertion cheaply.
7822   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7823           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7824     return Insertion;
7825   // Try inverting the insertion since for v2 masks it is easy to do and we
7826   // can't reliably sort the mask one way or the other.
7827   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7828   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7829           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7830     return Insertion;
7831
7832   // We have different paths for blend lowering, but they all must use the
7833   // *exact* same predicate.
7834   bool IsBlendSupported = Subtarget->hasSSE41();
7835   if (IsBlendSupported)
7836     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7837                                                   Subtarget, DAG))
7838       return Blend;
7839
7840   // Use dedicated unpack instructions for masks that match their pattern.
7841   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7842     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7843   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7844     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7845
7846   // Try to use byte rotation instructions.
7847   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7848   if (Subtarget->hasSSSE3())
7849     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7850             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7851       return Rotate;
7852
7853   // If we have direct support for blends, we should lower by decomposing into
7854   // a permute. That will be faster than the domain cross.
7855   if (IsBlendSupported)
7856     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7857                                                       Mask, DAG);
7858
7859   // We implement this with SHUFPD which is pretty lame because it will likely
7860   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7861   // However, all the alternatives are still more cycles and newer chips don't
7862   // have this problem. It would be really nice if x86 had better shuffles here.
7863   V1 = DAG.getBitcast(MVT::v2f64, V1);
7864   V2 = DAG.getBitcast(MVT::v2f64, V2);
7865   return DAG.getBitcast(MVT::v2i64,
7866                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7867 }
7868
7869 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7870 ///
7871 /// This is used to disable more specialized lowerings when the shufps lowering
7872 /// will happen to be efficient.
7873 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7874   // This routine only handles 128-bit shufps.
7875   assert(Mask.size() == 4 && "Unsupported mask size!");
7876
7877   // To lower with a single SHUFPS we need to have the low half and high half
7878   // each requiring a single input.
7879   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7880     return false;
7881   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7882     return false;
7883
7884   return true;
7885 }
7886
7887 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7888 ///
7889 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7890 /// It makes no assumptions about whether this is the *best* lowering, it simply
7891 /// uses it.
7892 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7893                                             ArrayRef<int> Mask, SDValue V1,
7894                                             SDValue V2, SelectionDAG &DAG) {
7895   SDValue LowV = V1, HighV = V2;
7896   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7897
7898   int NumV2Elements =
7899       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7900
7901   if (NumV2Elements == 1) {
7902     int V2Index =
7903         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7904         Mask.begin();
7905
7906     // Compute the index adjacent to V2Index and in the same half by toggling
7907     // the low bit.
7908     int V2AdjIndex = V2Index ^ 1;
7909
7910     if (Mask[V2AdjIndex] == -1) {
7911       // Handles all the cases where we have a single V2 element and an undef.
7912       // This will only ever happen in the high lanes because we commute the
7913       // vector otherwise.
7914       if (V2Index < 2)
7915         std::swap(LowV, HighV);
7916       NewMask[V2Index] -= 4;
7917     } else {
7918       // Handle the case where the V2 element ends up adjacent to a V1 element.
7919       // To make this work, blend them together as the first step.
7920       int V1Index = V2AdjIndex;
7921       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7922       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7923                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7924
7925       // Now proceed to reconstruct the final blend as we have the necessary
7926       // high or low half formed.
7927       if (V2Index < 2) {
7928         LowV = V2;
7929         HighV = V1;
7930       } else {
7931         HighV = V2;
7932       }
7933       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7934       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7935     }
7936   } else if (NumV2Elements == 2) {
7937     if (Mask[0] < 4 && Mask[1] < 4) {
7938       // Handle the easy case where we have V1 in the low lanes and V2 in the
7939       // high lanes.
7940       NewMask[2] -= 4;
7941       NewMask[3] -= 4;
7942     } else if (Mask[2] < 4 && Mask[3] < 4) {
7943       // We also handle the reversed case because this utility may get called
7944       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7945       // arrange things in the right direction.
7946       NewMask[0] -= 4;
7947       NewMask[1] -= 4;
7948       HighV = V1;
7949       LowV = V2;
7950     } else {
7951       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7952       // trying to place elements directly, just blend them and set up the final
7953       // shuffle to place them.
7954
7955       // The first two blend mask elements are for V1, the second two are for
7956       // V2.
7957       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7958                           Mask[2] < 4 ? Mask[2] : Mask[3],
7959                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7960                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7961       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7962                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7963
7964       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7965       // a blend.
7966       LowV = HighV = V1;
7967       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7968       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7969       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7970       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7971     }
7972   }
7973   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7974                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7975 }
7976
7977 /// \brief Lower 4-lane 32-bit floating point shuffles.
7978 ///
7979 /// Uses instructions exclusively from the floating point unit to minimize
7980 /// domain crossing penalties, as these are sufficient to implement all v4f32
7981 /// shuffles.
7982 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7983                                        const X86Subtarget *Subtarget,
7984                                        SelectionDAG &DAG) {
7985   SDLoc DL(Op);
7986   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7987   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7988   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7989   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7990   ArrayRef<int> Mask = SVOp->getMask();
7991   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7992
7993   int NumV2Elements =
7994       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7995
7996   if (NumV2Elements == 0) {
7997     // Check for being able to broadcast a single element.
7998     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7999                                                           Mask, Subtarget, DAG))
8000       return Broadcast;
8001
8002     // Use even/odd duplicate instructions for masks that match their pattern.
8003     if (Subtarget->hasSSE3()) {
8004       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8005         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8006       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8007         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8008     }
8009
8010     if (Subtarget->hasAVX()) {
8011       // If we have AVX, we can use VPERMILPS which will allow folding a load
8012       // into the shuffle.
8013       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8014                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8015     }
8016
8017     // Otherwise, use a straight shuffle of a single input vector. We pass the
8018     // input vector to both operands to simulate this with a SHUFPS.
8019     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8020                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8021   }
8022
8023   // There are special ways we can lower some single-element blends. However, we
8024   // have custom ways we can lower more complex single-element blends below that
8025   // we defer to if both this and BLENDPS fail to match, so restrict this to
8026   // when the V2 input is targeting element 0 of the mask -- that is the fast
8027   // case here.
8028   if (NumV2Elements == 1 && Mask[0] >= 4)
8029     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8030                                                          Mask, Subtarget, DAG))
8031       return V;
8032
8033   if (Subtarget->hasSSE41()) {
8034     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8035                                                   Subtarget, DAG))
8036       return Blend;
8037
8038     // Use INSERTPS if we can complete the shuffle efficiently.
8039     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8040       return V;
8041
8042     if (!isSingleSHUFPSMask(Mask))
8043       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8044               DL, MVT::v4f32, V1, V2, Mask, DAG))
8045         return BlendPerm;
8046   }
8047
8048   // Use dedicated unpack instructions for masks that match their pattern.
8049   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8050     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8051   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8052     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8053   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8054     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8055   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8056     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8057
8058   // Otherwise fall back to a SHUFPS lowering strategy.
8059   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8060 }
8061
8062 /// \brief Lower 4-lane i32 vector shuffles.
8063 ///
8064 /// We try to handle these with integer-domain shuffles where we can, but for
8065 /// blends we use the floating point domain blend instructions.
8066 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8067                                        const X86Subtarget *Subtarget,
8068                                        SelectionDAG &DAG) {
8069   SDLoc DL(Op);
8070   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8071   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8072   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8073   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8074   ArrayRef<int> Mask = SVOp->getMask();
8075   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8076
8077   // Whenever we can lower this as a zext, that instruction is strictly faster
8078   // than any alternative. It also allows us to fold memory operands into the
8079   // shuffle in many cases.
8080   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8081                                                          Mask, Subtarget, DAG))
8082     return ZExt;
8083
8084   int NumV2Elements =
8085       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8086
8087   if (NumV2Elements == 0) {
8088     // Check for being able to broadcast a single element.
8089     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8090                                                           Mask, Subtarget, DAG))
8091       return Broadcast;
8092
8093     // Straight shuffle of a single input vector. For everything from SSE2
8094     // onward this has a single fast instruction with no scary immediates.
8095     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8096     // but we aren't actually going to use the UNPCK instruction because doing
8097     // so prevents folding a load into this instruction or making a copy.
8098     const int UnpackLoMask[] = {0, 0, 1, 1};
8099     const int UnpackHiMask[] = {2, 2, 3, 3};
8100     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8101       Mask = UnpackLoMask;
8102     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8103       Mask = UnpackHiMask;
8104
8105     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8106                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8107   }
8108
8109   // Try to use shift instructions.
8110   if (SDValue Shift =
8111           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8112     return Shift;
8113
8114   // There are special ways we can lower some single-element blends.
8115   if (NumV2Elements == 1)
8116     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8117                                                          Mask, Subtarget, DAG))
8118       return V;
8119
8120   // We have different paths for blend lowering, but they all must use the
8121   // *exact* same predicate.
8122   bool IsBlendSupported = Subtarget->hasSSE41();
8123   if (IsBlendSupported)
8124     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8125                                                   Subtarget, DAG))
8126       return Blend;
8127
8128   if (SDValue Masked =
8129           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8130     return Masked;
8131
8132   // Use dedicated unpack instructions for masks that match their pattern.
8133   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8134     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8135   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8136     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8137   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8138     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8139   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8140     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8141
8142   // Try to use byte rotation instructions.
8143   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8144   if (Subtarget->hasSSSE3())
8145     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8146             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8147       return Rotate;
8148
8149   // If we have direct support for blends, we should lower by decomposing into
8150   // a permute. That will be faster than the domain cross.
8151   if (IsBlendSupported)
8152     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8153                                                       Mask, DAG);
8154
8155   // Try to lower by permuting the inputs into an unpack instruction.
8156   if (SDValue Unpack =
8157           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8158     return Unpack;
8159
8160   // We implement this with SHUFPS because it can blend from two vectors.
8161   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8162   // up the inputs, bypassing domain shift penalties that we would encur if we
8163   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8164   // relevant.
8165   return DAG.getBitcast(
8166       MVT::v4i32,
8167       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8168                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8169 }
8170
8171 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8172 /// shuffle lowering, and the most complex part.
8173 ///
8174 /// The lowering strategy is to try to form pairs of input lanes which are
8175 /// targeted at the same half of the final vector, and then use a dword shuffle
8176 /// to place them onto the right half, and finally unpack the paired lanes into
8177 /// their final position.
8178 ///
8179 /// The exact breakdown of how to form these dword pairs and align them on the
8180 /// correct sides is really tricky. See the comments within the function for
8181 /// more of the details.
8182 ///
8183 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8184 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8185 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8186 /// vector, form the analogous 128-bit 8-element Mask.
8187 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8188     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8189     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8190   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8191   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8192
8193   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8194   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8195   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8196
8197   SmallVector<int, 4> LoInputs;
8198   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8199                [](int M) { return M >= 0; });
8200   std::sort(LoInputs.begin(), LoInputs.end());
8201   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8202   SmallVector<int, 4> HiInputs;
8203   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8204                [](int M) { return M >= 0; });
8205   std::sort(HiInputs.begin(), HiInputs.end());
8206   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8207   int NumLToL =
8208       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8209   int NumHToL = LoInputs.size() - NumLToL;
8210   int NumLToH =
8211       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8212   int NumHToH = HiInputs.size() - NumLToH;
8213   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8214   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8215   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8216   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8217
8218   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8219   // such inputs we can swap two of the dwords across the half mark and end up
8220   // with <=2 inputs to each half in each half. Once there, we can fall through
8221   // to the generic code below. For example:
8222   //
8223   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8224   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8225   //
8226   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8227   // and an existing 2-into-2 on the other half. In this case we may have to
8228   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8229   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8230   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8231   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8232   // half than the one we target for fixing) will be fixed when we re-enter this
8233   // path. We will also combine away any sequence of PSHUFD instructions that
8234   // result into a single instruction. Here is an example of the tricky case:
8235   //
8236   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8237   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8238   //
8239   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8240   //
8241   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8242   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8243   //
8244   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8245   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8246   //
8247   // The result is fine to be handled by the generic logic.
8248   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8249                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8250                           int AOffset, int BOffset) {
8251     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8252            "Must call this with A having 3 or 1 inputs from the A half.");
8253     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8254            "Must call this with B having 1 or 3 inputs from the B half.");
8255     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8256            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8257
8258     // Compute the index of dword with only one word among the three inputs in
8259     // a half by taking the sum of the half with three inputs and subtracting
8260     // the sum of the actual three inputs. The difference is the remaining
8261     // slot.
8262     int ADWord, BDWord;
8263     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8264     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8265     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8266     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8267     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8268     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8269     int TripleNonInputIdx =
8270         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8271     TripleDWord = TripleNonInputIdx / 2;
8272
8273     // We use xor with one to compute the adjacent DWord to whichever one the
8274     // OneInput is in.
8275     OneInputDWord = (OneInput / 2) ^ 1;
8276
8277     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8278     // and BToA inputs. If there is also such a problem with the BToB and AToB
8279     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8280     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8281     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8282     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8283       // Compute how many inputs will be flipped by swapping these DWords. We
8284       // need
8285       // to balance this to ensure we don't form a 3-1 shuffle in the other
8286       // half.
8287       int NumFlippedAToBInputs =
8288           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8289           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8290       int NumFlippedBToBInputs =
8291           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8292           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8293       if ((NumFlippedAToBInputs == 1 &&
8294            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8295           (NumFlippedBToBInputs == 1 &&
8296            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8297         // We choose whether to fix the A half or B half based on whether that
8298         // half has zero flipped inputs. At zero, we may not be able to fix it
8299         // with that half. We also bias towards fixing the B half because that
8300         // will more commonly be the high half, and we have to bias one way.
8301         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8302                                                        ArrayRef<int> Inputs) {
8303           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8304           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8305                                          PinnedIdx ^ 1) != Inputs.end();
8306           // Determine whether the free index is in the flipped dword or the
8307           // unflipped dword based on where the pinned index is. We use this bit
8308           // in an xor to conditionally select the adjacent dword.
8309           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8310           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8311                                              FixFreeIdx) != Inputs.end();
8312           if (IsFixIdxInput == IsFixFreeIdxInput)
8313             FixFreeIdx += 1;
8314           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8315                                         FixFreeIdx) != Inputs.end();
8316           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8317                  "We need to be changing the number of flipped inputs!");
8318           int PSHUFHalfMask[] = {0, 1, 2, 3};
8319           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8320           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8321                           MVT::v8i16, V,
8322                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8323
8324           for (int &M : Mask)
8325             if (M != -1 && M == FixIdx)
8326               M = FixFreeIdx;
8327             else if (M != -1 && M == FixFreeIdx)
8328               M = FixIdx;
8329         };
8330         if (NumFlippedBToBInputs != 0) {
8331           int BPinnedIdx =
8332               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8333           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8334         } else {
8335           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8336           int APinnedIdx =
8337               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8338           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8339         }
8340       }
8341     }
8342
8343     int PSHUFDMask[] = {0, 1, 2, 3};
8344     PSHUFDMask[ADWord] = BDWord;
8345     PSHUFDMask[BDWord] = ADWord;
8346     V = DAG.getBitcast(
8347         VT,
8348         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8349                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8350
8351     // Adjust the mask to match the new locations of A and B.
8352     for (int &M : Mask)
8353       if (M != -1 && M/2 == ADWord)
8354         M = 2 * BDWord + M % 2;
8355       else if (M != -1 && M/2 == BDWord)
8356         M = 2 * ADWord + M % 2;
8357
8358     // Recurse back into this routine to re-compute state now that this isn't
8359     // a 3 and 1 problem.
8360     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8361                                                      DAG);
8362   };
8363   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8364     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8365   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8366     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8367
8368   // At this point there are at most two inputs to the low and high halves from
8369   // each half. That means the inputs can always be grouped into dwords and
8370   // those dwords can then be moved to the correct half with a dword shuffle.
8371   // We use at most one low and one high word shuffle to collect these paired
8372   // inputs into dwords, and finally a dword shuffle to place them.
8373   int PSHUFLMask[4] = {-1, -1, -1, -1};
8374   int PSHUFHMask[4] = {-1, -1, -1, -1};
8375   int PSHUFDMask[4] = {-1, -1, -1, -1};
8376
8377   // First fix the masks for all the inputs that are staying in their
8378   // original halves. This will then dictate the targets of the cross-half
8379   // shuffles.
8380   auto fixInPlaceInputs =
8381       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8382                     MutableArrayRef<int> SourceHalfMask,
8383                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8384     if (InPlaceInputs.empty())
8385       return;
8386     if (InPlaceInputs.size() == 1) {
8387       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8388           InPlaceInputs[0] - HalfOffset;
8389       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8390       return;
8391     }
8392     if (IncomingInputs.empty()) {
8393       // Just fix all of the in place inputs.
8394       for (int Input : InPlaceInputs) {
8395         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8396         PSHUFDMask[Input / 2] = Input / 2;
8397       }
8398       return;
8399     }
8400
8401     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8402     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8403         InPlaceInputs[0] - HalfOffset;
8404     // Put the second input next to the first so that they are packed into
8405     // a dword. We find the adjacent index by toggling the low bit.
8406     int AdjIndex = InPlaceInputs[0] ^ 1;
8407     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8408     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8409     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8410   };
8411   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8412   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8413
8414   // Now gather the cross-half inputs and place them into a free dword of
8415   // their target half.
8416   // FIXME: This operation could almost certainly be simplified dramatically to
8417   // look more like the 3-1 fixing operation.
8418   auto moveInputsToRightHalf = [&PSHUFDMask](
8419       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8420       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8421       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8422       int DestOffset) {
8423     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8424       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8425     };
8426     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8427                                                int Word) {
8428       int LowWord = Word & ~1;
8429       int HighWord = Word | 1;
8430       return isWordClobbered(SourceHalfMask, LowWord) ||
8431              isWordClobbered(SourceHalfMask, HighWord);
8432     };
8433
8434     if (IncomingInputs.empty())
8435       return;
8436
8437     if (ExistingInputs.empty()) {
8438       // Map any dwords with inputs from them into the right half.
8439       for (int Input : IncomingInputs) {
8440         // If the source half mask maps over the inputs, turn those into
8441         // swaps and use the swapped lane.
8442         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8443           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8444             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8445                 Input - SourceOffset;
8446             // We have to swap the uses in our half mask in one sweep.
8447             for (int &M : HalfMask)
8448               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8449                 M = Input;
8450               else if (M == Input)
8451                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8452           } else {
8453             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8454                        Input - SourceOffset &&
8455                    "Previous placement doesn't match!");
8456           }
8457           // Note that this correctly re-maps both when we do a swap and when
8458           // we observe the other side of the swap above. We rely on that to
8459           // avoid swapping the members of the input list directly.
8460           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8461         }
8462
8463         // Map the input's dword into the correct half.
8464         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8465           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8466         else
8467           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8468                      Input / 2 &&
8469                  "Previous placement doesn't match!");
8470       }
8471
8472       // And just directly shift any other-half mask elements to be same-half
8473       // as we will have mirrored the dword containing the element into the
8474       // same position within that half.
8475       for (int &M : HalfMask)
8476         if (M >= SourceOffset && M < SourceOffset + 4) {
8477           M = M - SourceOffset + DestOffset;
8478           assert(M >= 0 && "This should never wrap below zero!");
8479         }
8480       return;
8481     }
8482
8483     // Ensure we have the input in a viable dword of its current half. This
8484     // is particularly tricky because the original position may be clobbered
8485     // by inputs being moved and *staying* in that half.
8486     if (IncomingInputs.size() == 1) {
8487       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8488         int InputFixed = std::find(std::begin(SourceHalfMask),
8489                                    std::end(SourceHalfMask), -1) -
8490                          std::begin(SourceHalfMask) + SourceOffset;
8491         SourceHalfMask[InputFixed - SourceOffset] =
8492             IncomingInputs[0] - SourceOffset;
8493         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8494                      InputFixed);
8495         IncomingInputs[0] = InputFixed;
8496       }
8497     } else if (IncomingInputs.size() == 2) {
8498       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8499           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8500         // We have two non-adjacent or clobbered inputs we need to extract from
8501         // the source half. To do this, we need to map them into some adjacent
8502         // dword slot in the source mask.
8503         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8504                               IncomingInputs[1] - SourceOffset};
8505
8506         // If there is a free slot in the source half mask adjacent to one of
8507         // the inputs, place the other input in it. We use (Index XOR 1) to
8508         // compute an adjacent index.
8509         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8510             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8511           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8512           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8513           InputsFixed[1] = InputsFixed[0] ^ 1;
8514         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8515                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8516           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8517           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8518           InputsFixed[0] = InputsFixed[1] ^ 1;
8519         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8520                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8521           // The two inputs are in the same DWord but it is clobbered and the
8522           // adjacent DWord isn't used at all. Move both inputs to the free
8523           // slot.
8524           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8525           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8526           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8527           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8528         } else {
8529           // The only way we hit this point is if there is no clobbering
8530           // (because there are no off-half inputs to this half) and there is no
8531           // free slot adjacent to one of the inputs. In this case, we have to
8532           // swap an input with a non-input.
8533           for (int i = 0; i < 4; ++i)
8534             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8535                    "We can't handle any clobbers here!");
8536           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8537                  "Cannot have adjacent inputs here!");
8538
8539           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8540           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8541
8542           // We also have to update the final source mask in this case because
8543           // it may need to undo the above swap.
8544           for (int &M : FinalSourceHalfMask)
8545             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8546               M = InputsFixed[1] + SourceOffset;
8547             else if (M == InputsFixed[1] + SourceOffset)
8548               M = (InputsFixed[0] ^ 1) + SourceOffset;
8549
8550           InputsFixed[1] = InputsFixed[0] ^ 1;
8551         }
8552
8553         // Point everything at the fixed inputs.
8554         for (int &M : HalfMask)
8555           if (M == IncomingInputs[0])
8556             M = InputsFixed[0] + SourceOffset;
8557           else if (M == IncomingInputs[1])
8558             M = InputsFixed[1] + SourceOffset;
8559
8560         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8561         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8562       }
8563     } else {
8564       llvm_unreachable("Unhandled input size!");
8565     }
8566
8567     // Now hoist the DWord down to the right half.
8568     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8569     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8570     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8571     for (int &M : HalfMask)
8572       for (int Input : IncomingInputs)
8573         if (M == Input)
8574           M = FreeDWord * 2 + Input % 2;
8575   };
8576   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8577                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8578   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8579                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8580
8581   // Now enact all the shuffles we've computed to move the inputs into their
8582   // target half.
8583   if (!isNoopShuffleMask(PSHUFLMask))
8584     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8585                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8586   if (!isNoopShuffleMask(PSHUFHMask))
8587     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8588                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8589   if (!isNoopShuffleMask(PSHUFDMask))
8590     V = DAG.getBitcast(
8591         VT,
8592         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8593                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8594
8595   // At this point, each half should contain all its inputs, and we can then
8596   // just shuffle them into their final position.
8597   assert(std::count_if(LoMask.begin(), LoMask.end(),
8598                        [](int M) { return M >= 4; }) == 0 &&
8599          "Failed to lift all the high half inputs to the low mask!");
8600   assert(std::count_if(HiMask.begin(), HiMask.end(),
8601                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8602          "Failed to lift all the low half inputs to the high mask!");
8603
8604   // Do a half shuffle for the low mask.
8605   if (!isNoopShuffleMask(LoMask))
8606     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8607                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8608
8609   // Do a half shuffle with the high mask after shifting its values down.
8610   for (int &M : HiMask)
8611     if (M >= 0)
8612       M -= 4;
8613   if (!isNoopShuffleMask(HiMask))
8614     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8615                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8616
8617   return V;
8618 }
8619
8620 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8621 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8622                                           SDValue V2, ArrayRef<int> Mask,
8623                                           SelectionDAG &DAG, bool &V1InUse,
8624                                           bool &V2InUse) {
8625   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8626   SDValue V1Mask[16];
8627   SDValue V2Mask[16];
8628   V1InUse = false;
8629   V2InUse = false;
8630
8631   int Size = Mask.size();
8632   int Scale = 16 / Size;
8633   for (int i = 0; i < 16; ++i) {
8634     if (Mask[i / Scale] == -1) {
8635       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8636     } else {
8637       const int ZeroMask = 0x80;
8638       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8639                                           : ZeroMask;
8640       int V2Idx = Mask[i / Scale] < Size
8641                       ? ZeroMask
8642                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8643       if (Zeroable[i / Scale])
8644         V1Idx = V2Idx = ZeroMask;
8645       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8646       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8647       V1InUse |= (ZeroMask != V1Idx);
8648       V2InUse |= (ZeroMask != V2Idx);
8649     }
8650   }
8651
8652   if (V1InUse)
8653     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8654                      DAG.getBitcast(MVT::v16i8, V1),
8655                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8656   if (V2InUse)
8657     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8658                      DAG.getBitcast(MVT::v16i8, V2),
8659                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8660
8661   // If we need shuffled inputs from both, blend the two.
8662   SDValue V;
8663   if (V1InUse && V2InUse)
8664     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8665   else
8666     V = V1InUse ? V1 : V2;
8667
8668   // Cast the result back to the correct type.
8669   return DAG.getBitcast(VT, V);
8670 }
8671
8672 /// \brief Generic lowering of 8-lane i16 shuffles.
8673 ///
8674 /// This handles both single-input shuffles and combined shuffle/blends with
8675 /// two inputs. The single input shuffles are immediately delegated to
8676 /// a dedicated lowering routine.
8677 ///
8678 /// The blends are lowered in one of three fundamental ways. If there are few
8679 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8680 /// of the input is significantly cheaper when lowered as an interleaving of
8681 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8682 /// halves of the inputs separately (making them have relatively few inputs)
8683 /// and then concatenate them.
8684 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8685                                        const X86Subtarget *Subtarget,
8686                                        SelectionDAG &DAG) {
8687   SDLoc DL(Op);
8688   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8689   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8690   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8691   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8692   ArrayRef<int> OrigMask = SVOp->getMask();
8693   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8694                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8695   MutableArrayRef<int> Mask(MaskStorage);
8696
8697   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8698
8699   // Whenever we can lower this as a zext, that instruction is strictly faster
8700   // than any alternative.
8701   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8702           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8703     return ZExt;
8704
8705   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8706   (void)isV1;
8707   auto isV2 = [](int M) { return M >= 8; };
8708
8709   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8710
8711   if (NumV2Inputs == 0) {
8712     // Check for being able to broadcast a single element.
8713     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8714                                                           Mask, Subtarget, DAG))
8715       return Broadcast;
8716
8717     // Try to use shift instructions.
8718     if (SDValue Shift =
8719             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8720       return Shift;
8721
8722     // Use dedicated unpack instructions for masks that match their pattern.
8723     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8724       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8725     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8726       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8727
8728     // Try to use byte rotation instructions.
8729     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8730                                                         Mask, Subtarget, DAG))
8731       return Rotate;
8732
8733     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8734                                                      Subtarget, DAG);
8735   }
8736
8737   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8738          "All single-input shuffles should be canonicalized to be V1-input "
8739          "shuffles.");
8740
8741   // Try to use shift instructions.
8742   if (SDValue Shift =
8743           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8744     return Shift;
8745
8746   // See if we can use SSE4A Extraction / Insertion.
8747   if (Subtarget->hasSSE4A())
8748     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8749       return V;
8750
8751   // There are special ways we can lower some single-element blends.
8752   if (NumV2Inputs == 1)
8753     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8754                                                          Mask, Subtarget, DAG))
8755       return V;
8756
8757   // We have different paths for blend lowering, but they all must use the
8758   // *exact* same predicate.
8759   bool IsBlendSupported = Subtarget->hasSSE41();
8760   if (IsBlendSupported)
8761     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8762                                                   Subtarget, DAG))
8763       return Blend;
8764
8765   if (SDValue Masked =
8766           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8767     return Masked;
8768
8769   // Use dedicated unpack instructions for masks that match their pattern.
8770   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8771     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8772   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8773     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8774
8775   // Try to use byte rotation instructions.
8776   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8777           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8778     return Rotate;
8779
8780   if (SDValue BitBlend =
8781           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8782     return BitBlend;
8783
8784   if (SDValue Unpack =
8785           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8786     return Unpack;
8787
8788   // If we can't directly blend but can use PSHUFB, that will be better as it
8789   // can both shuffle and set up the inefficient blend.
8790   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8791     bool V1InUse, V2InUse;
8792     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8793                                       V1InUse, V2InUse);
8794   }
8795
8796   // We can always bit-blend if we have to so the fallback strategy is to
8797   // decompose into single-input permutes and blends.
8798   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8799                                                       Mask, DAG);
8800 }
8801
8802 /// \brief Check whether a compaction lowering can be done by dropping even
8803 /// elements and compute how many times even elements must be dropped.
8804 ///
8805 /// This handles shuffles which take every Nth element where N is a power of
8806 /// two. Example shuffle masks:
8807 ///
8808 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8809 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8810 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8811 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8812 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8813 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8814 ///
8815 /// Any of these lanes can of course be undef.
8816 ///
8817 /// This routine only supports N <= 3.
8818 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8819 /// for larger N.
8820 ///
8821 /// \returns N above, or the number of times even elements must be dropped if
8822 /// there is such a number. Otherwise returns zero.
8823 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8824   // Figure out whether we're looping over two inputs or just one.
8825   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8826
8827   // The modulus for the shuffle vector entries is based on whether this is
8828   // a single input or not.
8829   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8830   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8831          "We should only be called with masks with a power-of-2 size!");
8832
8833   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8834
8835   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8836   // and 2^3 simultaneously. This is because we may have ambiguity with
8837   // partially undef inputs.
8838   bool ViableForN[3] = {true, true, true};
8839
8840   for (int i = 0, e = Mask.size(); i < e; ++i) {
8841     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8842     // want.
8843     if (Mask[i] == -1)
8844       continue;
8845
8846     bool IsAnyViable = false;
8847     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8848       if (ViableForN[j]) {
8849         uint64_t N = j + 1;
8850
8851         // The shuffle mask must be equal to (i * 2^N) % M.
8852         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8853           IsAnyViable = true;
8854         else
8855           ViableForN[j] = false;
8856       }
8857     // Early exit if we exhaust the possible powers of two.
8858     if (!IsAnyViable)
8859       break;
8860   }
8861
8862   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8863     if (ViableForN[j])
8864       return j + 1;
8865
8866   // Return 0 as there is no viable power of two.
8867   return 0;
8868 }
8869
8870 /// \brief Generic lowering of v16i8 shuffles.
8871 ///
8872 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8873 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8874 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8875 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8876 /// back together.
8877 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8878                                        const X86Subtarget *Subtarget,
8879                                        SelectionDAG &DAG) {
8880   SDLoc DL(Op);
8881   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8882   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8883   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8884   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8885   ArrayRef<int> Mask = SVOp->getMask();
8886   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8887
8888   // Try to use shift instructions.
8889   if (SDValue Shift =
8890           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8891     return Shift;
8892
8893   // Try to use byte rotation instructions.
8894   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8895           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8896     return Rotate;
8897
8898   // Try to use a zext lowering.
8899   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8900           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8901     return ZExt;
8902
8903   // See if we can use SSE4A Extraction / Insertion.
8904   if (Subtarget->hasSSE4A())
8905     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8906       return V;
8907
8908   int NumV2Elements =
8909       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8910
8911   // For single-input shuffles, there are some nicer lowering tricks we can use.
8912   if (NumV2Elements == 0) {
8913     // Check for being able to broadcast a single element.
8914     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8915                                                           Mask, Subtarget, DAG))
8916       return Broadcast;
8917
8918     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8919     // Notably, this handles splat and partial-splat shuffles more efficiently.
8920     // However, it only makes sense if the pre-duplication shuffle simplifies
8921     // things significantly. Currently, this means we need to be able to
8922     // express the pre-duplication shuffle as an i16 shuffle.
8923     //
8924     // FIXME: We should check for other patterns which can be widened into an
8925     // i16 shuffle as well.
8926     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8927       for (int i = 0; i < 16; i += 2)
8928         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8929           return false;
8930
8931       return true;
8932     };
8933     auto tryToWidenViaDuplication = [&]() -> SDValue {
8934       if (!canWidenViaDuplication(Mask))
8935         return SDValue();
8936       SmallVector<int, 4> LoInputs;
8937       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8938                    [](int M) { return M >= 0 && M < 8; });
8939       std::sort(LoInputs.begin(), LoInputs.end());
8940       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8941                      LoInputs.end());
8942       SmallVector<int, 4> HiInputs;
8943       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8944                    [](int M) { return M >= 8; });
8945       std::sort(HiInputs.begin(), HiInputs.end());
8946       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8947                      HiInputs.end());
8948
8949       bool TargetLo = LoInputs.size() >= HiInputs.size();
8950       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8951       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8952
8953       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8954       SmallDenseMap<int, int, 8> LaneMap;
8955       for (int I : InPlaceInputs) {
8956         PreDupI16Shuffle[I/2] = I/2;
8957         LaneMap[I] = I;
8958       }
8959       int j = TargetLo ? 0 : 4, je = j + 4;
8960       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8961         // Check if j is already a shuffle of this input. This happens when
8962         // there are two adjacent bytes after we move the low one.
8963         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8964           // If we haven't yet mapped the input, search for a slot into which
8965           // we can map it.
8966           while (j < je && PreDupI16Shuffle[j] != -1)
8967             ++j;
8968
8969           if (j == je)
8970             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8971             return SDValue();
8972
8973           // Map this input with the i16 shuffle.
8974           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8975         }
8976
8977         // Update the lane map based on the mapping we ended up with.
8978         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8979       }
8980       V1 = DAG.getBitcast(
8981           MVT::v16i8,
8982           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
8983                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8984
8985       // Unpack the bytes to form the i16s that will be shuffled into place.
8986       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8987                        MVT::v16i8, V1, V1);
8988
8989       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8990       for (int i = 0; i < 16; ++i)
8991         if (Mask[i] != -1) {
8992           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8993           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8994           if (PostDupI16Shuffle[i / 2] == -1)
8995             PostDupI16Shuffle[i / 2] = MappedMask;
8996           else
8997             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8998                    "Conflicting entrties in the original shuffle!");
8999         }
9000       return DAG.getBitcast(
9001           MVT::v16i8,
9002           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9003                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9004     };
9005     if (SDValue V = tryToWidenViaDuplication())
9006       return V;
9007   }
9008
9009   // Use dedicated unpack instructions for masks that match their pattern.
9010   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9011                                          0, 16, 1, 17, 2, 18, 3, 19,
9012                                          // High half.
9013                                          4, 20, 5, 21, 6, 22, 7, 23}))
9014     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9015   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9016                                          8, 24, 9, 25, 10, 26, 11, 27,
9017                                          // High half.
9018                                          12, 28, 13, 29, 14, 30, 15, 31}))
9019     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9020
9021   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9022   // with PSHUFB. It is important to do this before we attempt to generate any
9023   // blends but after all of the single-input lowerings. If the single input
9024   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9025   // want to preserve that and we can DAG combine any longer sequences into
9026   // a PSHUFB in the end. But once we start blending from multiple inputs,
9027   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9028   // and there are *very* few patterns that would actually be faster than the
9029   // PSHUFB approach because of its ability to zero lanes.
9030   //
9031   // FIXME: The only exceptions to the above are blends which are exact
9032   // interleavings with direct instructions supporting them. We currently don't
9033   // handle those well here.
9034   if (Subtarget->hasSSSE3()) {
9035     bool V1InUse = false;
9036     bool V2InUse = false;
9037
9038     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9039                                                 DAG, V1InUse, V2InUse);
9040
9041     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9042     // do so. This avoids using them to handle blends-with-zero which is
9043     // important as a single pshufb is significantly faster for that.
9044     if (V1InUse && V2InUse) {
9045       if (Subtarget->hasSSE41())
9046         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9047                                                       Mask, Subtarget, DAG))
9048           return Blend;
9049
9050       // We can use an unpack to do the blending rather than an or in some
9051       // cases. Even though the or may be (very minorly) more efficient, we
9052       // preference this lowering because there are common cases where part of
9053       // the complexity of the shuffles goes away when we do the final blend as
9054       // an unpack.
9055       // FIXME: It might be worth trying to detect if the unpack-feeding
9056       // shuffles will both be pshufb, in which case we shouldn't bother with
9057       // this.
9058       if (SDValue Unpack =
9059               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9060         return Unpack;
9061     }
9062
9063     return PSHUFB;
9064   }
9065
9066   // There are special ways we can lower some single-element blends.
9067   if (NumV2Elements == 1)
9068     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9069                                                          Mask, Subtarget, DAG))
9070       return V;
9071
9072   if (SDValue BitBlend =
9073           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9074     return BitBlend;
9075
9076   // Check whether a compaction lowering can be done. This handles shuffles
9077   // which take every Nth element for some even N. See the helper function for
9078   // details.
9079   //
9080   // We special case these as they can be particularly efficiently handled with
9081   // the PACKUSB instruction on x86 and they show up in common patterns of
9082   // rearranging bytes to truncate wide elements.
9083   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9084     // NumEvenDrops is the power of two stride of the elements. Another way of
9085     // thinking about it is that we need to drop the even elements this many
9086     // times to get the original input.
9087     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9088
9089     // First we need to zero all the dropped bytes.
9090     assert(NumEvenDrops <= 3 &&
9091            "No support for dropping even elements more than 3 times.");
9092     // We use the mask type to pick which bytes are preserved based on how many
9093     // elements are dropped.
9094     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9095     SDValue ByteClearMask = DAG.getBitcast(
9096         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9097     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9098     if (!IsSingleInput)
9099       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9100
9101     // Now pack things back together.
9102     V1 = DAG.getBitcast(MVT::v8i16, V1);
9103     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9104     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9105     for (int i = 1; i < NumEvenDrops; ++i) {
9106       Result = DAG.getBitcast(MVT::v8i16, Result);
9107       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9108     }
9109
9110     return Result;
9111   }
9112
9113   // Handle multi-input cases by blending single-input shuffles.
9114   if (NumV2Elements > 0)
9115     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9116                                                       Mask, DAG);
9117
9118   // The fallback path for single-input shuffles widens this into two v8i16
9119   // vectors with unpacks, shuffles those, and then pulls them back together
9120   // with a pack.
9121   SDValue V = V1;
9122
9123   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9124   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9125   for (int i = 0; i < 16; ++i)
9126     if (Mask[i] >= 0)
9127       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9128
9129   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9130
9131   SDValue VLoHalf, VHiHalf;
9132   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9133   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9134   // i16s.
9135   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9136                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9137       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9138                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9139     // Use a mask to drop the high bytes.
9140     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9141     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9142                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9143
9144     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9145     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9146
9147     // Squash the masks to point directly into VLoHalf.
9148     for (int &M : LoBlendMask)
9149       if (M >= 0)
9150         M /= 2;
9151     for (int &M : HiBlendMask)
9152       if (M >= 0)
9153         M /= 2;
9154   } else {
9155     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9156     // VHiHalf so that we can blend them as i16s.
9157     VLoHalf = DAG.getBitcast(
9158         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9159     VHiHalf = DAG.getBitcast(
9160         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9161   }
9162
9163   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9164   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9165
9166   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9167 }
9168
9169 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9170 ///
9171 /// This routine breaks down the specific type of 128-bit shuffle and
9172 /// dispatches to the lowering routines accordingly.
9173 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9174                                         MVT VT, const X86Subtarget *Subtarget,
9175                                         SelectionDAG &DAG) {
9176   switch (VT.SimpleTy) {
9177   case MVT::v2i64:
9178     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9179   case MVT::v2f64:
9180     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9181   case MVT::v4i32:
9182     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9183   case MVT::v4f32:
9184     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9185   case MVT::v8i16:
9186     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9187   case MVT::v16i8:
9188     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9189
9190   default:
9191     llvm_unreachable("Unimplemented!");
9192   }
9193 }
9194
9195 /// \brief Helper function to test whether a shuffle mask could be
9196 /// simplified by widening the elements being shuffled.
9197 ///
9198 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9199 /// leaves it in an unspecified state.
9200 ///
9201 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9202 /// shuffle masks. The latter have the special property of a '-2' representing
9203 /// a zero-ed lane of a vector.
9204 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9205                                     SmallVectorImpl<int> &WidenedMask) {
9206   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9207     // If both elements are undef, its trivial.
9208     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9209       WidenedMask.push_back(SM_SentinelUndef);
9210       continue;
9211     }
9212
9213     // Check for an undef mask and a mask value properly aligned to fit with
9214     // a pair of values. If we find such a case, use the non-undef mask's value.
9215     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9216       WidenedMask.push_back(Mask[i + 1] / 2);
9217       continue;
9218     }
9219     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9220       WidenedMask.push_back(Mask[i] / 2);
9221       continue;
9222     }
9223
9224     // When zeroing, we need to spread the zeroing across both lanes to widen.
9225     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9226       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9227           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9228         WidenedMask.push_back(SM_SentinelZero);
9229         continue;
9230       }
9231       return false;
9232     }
9233
9234     // Finally check if the two mask values are adjacent and aligned with
9235     // a pair.
9236     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9237       WidenedMask.push_back(Mask[i] / 2);
9238       continue;
9239     }
9240
9241     // Otherwise we can't safely widen the elements used in this shuffle.
9242     return false;
9243   }
9244   assert(WidenedMask.size() == Mask.size() / 2 &&
9245          "Incorrect size of mask after widening the elements!");
9246
9247   return true;
9248 }
9249
9250 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9251 ///
9252 /// This routine just extracts two subvectors, shuffles them independently, and
9253 /// then concatenates them back together. This should work effectively with all
9254 /// AVX vector shuffle types.
9255 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9256                                           SDValue V2, ArrayRef<int> Mask,
9257                                           SelectionDAG &DAG) {
9258   assert(VT.getSizeInBits() >= 256 &&
9259          "Only for 256-bit or wider vector shuffles!");
9260   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9261   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9262
9263   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9264   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9265
9266   int NumElements = VT.getVectorNumElements();
9267   int SplitNumElements = NumElements / 2;
9268   MVT ScalarVT = VT.getScalarType();
9269   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9270
9271   // Rather than splitting build-vectors, just build two narrower build
9272   // vectors. This helps shuffling with splats and zeros.
9273   auto SplitVector = [&](SDValue V) {
9274     while (V.getOpcode() == ISD::BITCAST)
9275       V = V->getOperand(0);
9276
9277     MVT OrigVT = V.getSimpleValueType();
9278     int OrigNumElements = OrigVT.getVectorNumElements();
9279     int OrigSplitNumElements = OrigNumElements / 2;
9280     MVT OrigScalarVT = OrigVT.getScalarType();
9281     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9282
9283     SDValue LoV, HiV;
9284
9285     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9286     if (!BV) {
9287       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9288                         DAG.getIntPtrConstant(0, DL));
9289       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9290                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9291     } else {
9292
9293       SmallVector<SDValue, 16> LoOps, HiOps;
9294       for (int i = 0; i < OrigSplitNumElements; ++i) {
9295         LoOps.push_back(BV->getOperand(i));
9296         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9297       }
9298       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9299       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9300     }
9301     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9302                           DAG.getBitcast(SplitVT, HiV));
9303   };
9304
9305   SDValue LoV1, HiV1, LoV2, HiV2;
9306   std::tie(LoV1, HiV1) = SplitVector(V1);
9307   std::tie(LoV2, HiV2) = SplitVector(V2);
9308
9309   // Now create two 4-way blends of these half-width vectors.
9310   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9311     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9312     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9313     for (int i = 0; i < SplitNumElements; ++i) {
9314       int M = HalfMask[i];
9315       if (M >= NumElements) {
9316         if (M >= NumElements + SplitNumElements)
9317           UseHiV2 = true;
9318         else
9319           UseLoV2 = true;
9320         V2BlendMask.push_back(M - NumElements);
9321         V1BlendMask.push_back(-1);
9322         BlendMask.push_back(SplitNumElements + i);
9323       } else if (M >= 0) {
9324         if (M >= SplitNumElements)
9325           UseHiV1 = true;
9326         else
9327           UseLoV1 = true;
9328         V2BlendMask.push_back(-1);
9329         V1BlendMask.push_back(M);
9330         BlendMask.push_back(i);
9331       } else {
9332         V2BlendMask.push_back(-1);
9333         V1BlendMask.push_back(-1);
9334         BlendMask.push_back(-1);
9335       }
9336     }
9337
9338     // Because the lowering happens after all combining takes place, we need to
9339     // manually combine these blend masks as much as possible so that we create
9340     // a minimal number of high-level vector shuffle nodes.
9341
9342     // First try just blending the halves of V1 or V2.
9343     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9344       return DAG.getUNDEF(SplitVT);
9345     if (!UseLoV2 && !UseHiV2)
9346       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9347     if (!UseLoV1 && !UseHiV1)
9348       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9349
9350     SDValue V1Blend, V2Blend;
9351     if (UseLoV1 && UseHiV1) {
9352       V1Blend =
9353         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9354     } else {
9355       // We only use half of V1 so map the usage down into the final blend mask.
9356       V1Blend = UseLoV1 ? LoV1 : HiV1;
9357       for (int i = 0; i < SplitNumElements; ++i)
9358         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9359           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9360     }
9361     if (UseLoV2 && UseHiV2) {
9362       V2Blend =
9363         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9364     } else {
9365       // We only use half of V2 so map the usage down into the final blend mask.
9366       V2Blend = UseLoV2 ? LoV2 : HiV2;
9367       for (int i = 0; i < SplitNumElements; ++i)
9368         if (BlendMask[i] >= SplitNumElements)
9369           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9370     }
9371     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9372   };
9373   SDValue Lo = HalfBlend(LoMask);
9374   SDValue Hi = HalfBlend(HiMask);
9375   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9376 }
9377
9378 /// \brief Either split a vector in halves or decompose the shuffles and the
9379 /// blend.
9380 ///
9381 /// This is provided as a good fallback for many lowerings of non-single-input
9382 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9383 /// between splitting the shuffle into 128-bit components and stitching those
9384 /// back together vs. extracting the single-input shuffles and blending those
9385 /// results.
9386 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9387                                                 SDValue V2, ArrayRef<int> Mask,
9388                                                 SelectionDAG &DAG) {
9389   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9390                                             "lower single-input shuffles as it "
9391                                             "could then recurse on itself.");
9392   int Size = Mask.size();
9393
9394   // If this can be modeled as a broadcast of two elements followed by a blend,
9395   // prefer that lowering. This is especially important because broadcasts can
9396   // often fold with memory operands.
9397   auto DoBothBroadcast = [&] {
9398     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9399     for (int M : Mask)
9400       if (M >= Size) {
9401         if (V2BroadcastIdx == -1)
9402           V2BroadcastIdx = M - Size;
9403         else if (M - Size != V2BroadcastIdx)
9404           return false;
9405       } else if (M >= 0) {
9406         if (V1BroadcastIdx == -1)
9407           V1BroadcastIdx = M;
9408         else if (M != V1BroadcastIdx)
9409           return false;
9410       }
9411     return true;
9412   };
9413   if (DoBothBroadcast())
9414     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9415                                                       DAG);
9416
9417   // If the inputs all stem from a single 128-bit lane of each input, then we
9418   // split them rather than blending because the split will decompose to
9419   // unusually few instructions.
9420   int LaneCount = VT.getSizeInBits() / 128;
9421   int LaneSize = Size / LaneCount;
9422   SmallBitVector LaneInputs[2];
9423   LaneInputs[0].resize(LaneCount, false);
9424   LaneInputs[1].resize(LaneCount, false);
9425   for (int i = 0; i < Size; ++i)
9426     if (Mask[i] >= 0)
9427       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9428   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9429     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9430
9431   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9432   // that the decomposed single-input shuffles don't end up here.
9433   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9434 }
9435
9436 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9437 /// a permutation and blend of those lanes.
9438 ///
9439 /// This essentially blends the out-of-lane inputs to each lane into the lane
9440 /// from a permuted copy of the vector. This lowering strategy results in four
9441 /// instructions in the worst case for a single-input cross lane shuffle which
9442 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9443 /// of. Special cases for each particular shuffle pattern should be handled
9444 /// prior to trying this lowering.
9445 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9446                                                        SDValue V1, SDValue V2,
9447                                                        ArrayRef<int> Mask,
9448                                                        SelectionDAG &DAG) {
9449   // FIXME: This should probably be generalized for 512-bit vectors as well.
9450   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9451   int LaneSize = Mask.size() / 2;
9452
9453   // If there are only inputs from one 128-bit lane, splitting will in fact be
9454   // less expensive. The flags track whether the given lane contains an element
9455   // that crosses to another lane.
9456   bool LaneCrossing[2] = {false, false};
9457   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9458     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9459       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9460   if (!LaneCrossing[0] || !LaneCrossing[1])
9461     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9462
9463   if (isSingleInputShuffleMask(Mask)) {
9464     SmallVector<int, 32> FlippedBlendMask;
9465     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9466       FlippedBlendMask.push_back(
9467           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9468                                   ? Mask[i]
9469                                   : Mask[i] % LaneSize +
9470                                         (i / LaneSize) * LaneSize + Size));
9471
9472     // Flip the vector, and blend the results which should now be in-lane. The
9473     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9474     // 5 for the high source. The value 3 selects the high half of source 2 and
9475     // the value 2 selects the low half of source 2. We only use source 2 to
9476     // allow folding it into a memory operand.
9477     unsigned PERMMask = 3 | 2 << 4;
9478     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9479                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9480     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9481   }
9482
9483   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9484   // will be handled by the above logic and a blend of the results, much like
9485   // other patterns in AVX.
9486   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9487 }
9488
9489 /// \brief Handle lowering 2-lane 128-bit shuffles.
9490 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9491                                         SDValue V2, ArrayRef<int> Mask,
9492                                         const X86Subtarget *Subtarget,
9493                                         SelectionDAG &DAG) {
9494   // TODO: If minimizing size and one of the inputs is a zero vector and the
9495   // the zero vector has only one use, we could use a VPERM2X128 to save the
9496   // instruction bytes needed to explicitly generate the zero vector.
9497
9498   // Blends are faster and handle all the non-lane-crossing cases.
9499   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9500                                                 Subtarget, DAG))
9501     return Blend;
9502
9503   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9504   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9505
9506   // If either input operand is a zero vector, use VPERM2X128 because its mask
9507   // allows us to replace the zero input with an implicit zero.
9508   if (!IsV1Zero && !IsV2Zero) {
9509     // Check for patterns which can be matched with a single insert of a 128-bit
9510     // subvector.
9511     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9512     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9513       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9514                                    VT.getVectorNumElements() / 2);
9515       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9516                                 DAG.getIntPtrConstant(0, DL));
9517       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9518                                 OnlyUsesV1 ? V1 : V2,
9519                                 DAG.getIntPtrConstant(0, DL));
9520       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9521     }
9522   }
9523
9524   // Otherwise form a 128-bit permutation. After accounting for undefs,
9525   // convert the 64-bit shuffle mask selection values into 128-bit
9526   // selection bits by dividing the indexes by 2 and shifting into positions
9527   // defined by a vperm2*128 instruction's immediate control byte.
9528
9529   // The immediate permute control byte looks like this:
9530   //    [1:0] - select 128 bits from sources for low half of destination
9531   //    [2]   - ignore
9532   //    [3]   - zero low half of destination
9533   //    [5:4] - select 128 bits from sources for high half of destination
9534   //    [6]   - ignore
9535   //    [7]   - zero high half of destination
9536
9537   int MaskLO = Mask[0];
9538   if (MaskLO == SM_SentinelUndef)
9539     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9540
9541   int MaskHI = Mask[2];
9542   if (MaskHI == SM_SentinelUndef)
9543     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9544
9545   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9546
9547   // If either input is a zero vector, replace it with an undef input.
9548   // Shuffle mask values <  4 are selecting elements of V1.
9549   // Shuffle mask values >= 4 are selecting elements of V2.
9550   // Adjust each half of the permute mask by clearing the half that was
9551   // selecting the zero vector and setting the zero mask bit.
9552   if (IsV1Zero) {
9553     V1 = DAG.getUNDEF(VT);
9554     if (MaskLO < 4)
9555       PermMask = (PermMask & 0xf0) | 0x08;
9556     if (MaskHI < 4)
9557       PermMask = (PermMask & 0x0f) | 0x80;
9558   }
9559   if (IsV2Zero) {
9560     V2 = DAG.getUNDEF(VT);
9561     if (MaskLO >= 4)
9562       PermMask = (PermMask & 0xf0) | 0x08;
9563     if (MaskHI >= 4)
9564       PermMask = (PermMask & 0x0f) | 0x80;
9565   }
9566
9567   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9568                      DAG.getConstant(PermMask, DL, MVT::i8));
9569 }
9570
9571 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9572 /// shuffling each lane.
9573 ///
9574 /// This will only succeed when the result of fixing the 128-bit lanes results
9575 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9576 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9577 /// the lane crosses early and then use simpler shuffles within each lane.
9578 ///
9579 /// FIXME: It might be worthwhile at some point to support this without
9580 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9581 /// in x86 only floating point has interesting non-repeating shuffles, and even
9582 /// those are still *marginally* more expensive.
9583 static SDValue lowerVectorShuffleByMerging128BitLanes(
9584     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9585     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9586   assert(!isSingleInputShuffleMask(Mask) &&
9587          "This is only useful with multiple inputs.");
9588
9589   int Size = Mask.size();
9590   int LaneSize = 128 / VT.getScalarSizeInBits();
9591   int NumLanes = Size / LaneSize;
9592   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9593
9594   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9595   // check whether the in-128-bit lane shuffles share a repeating pattern.
9596   SmallVector<int, 4> Lanes;
9597   Lanes.resize(NumLanes, -1);
9598   SmallVector<int, 4> InLaneMask;
9599   InLaneMask.resize(LaneSize, -1);
9600   for (int i = 0; i < Size; ++i) {
9601     if (Mask[i] < 0)
9602       continue;
9603
9604     int j = i / LaneSize;
9605
9606     if (Lanes[j] < 0) {
9607       // First entry we've seen for this lane.
9608       Lanes[j] = Mask[i] / LaneSize;
9609     } else if (Lanes[j] != Mask[i] / LaneSize) {
9610       // This doesn't match the lane selected previously!
9611       return SDValue();
9612     }
9613
9614     // Check that within each lane we have a consistent shuffle mask.
9615     int k = i % LaneSize;
9616     if (InLaneMask[k] < 0) {
9617       InLaneMask[k] = Mask[i] % LaneSize;
9618     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9619       // This doesn't fit a repeating in-lane mask.
9620       return SDValue();
9621     }
9622   }
9623
9624   // First shuffle the lanes into place.
9625   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9626                                 VT.getSizeInBits() / 64);
9627   SmallVector<int, 8> LaneMask;
9628   LaneMask.resize(NumLanes * 2, -1);
9629   for (int i = 0; i < NumLanes; ++i)
9630     if (Lanes[i] >= 0) {
9631       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9632       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9633     }
9634
9635   V1 = DAG.getBitcast(LaneVT, V1);
9636   V2 = DAG.getBitcast(LaneVT, V2);
9637   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9638
9639   // Cast it back to the type we actually want.
9640   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9641
9642   // Now do a simple shuffle that isn't lane crossing.
9643   SmallVector<int, 8> NewMask;
9644   NewMask.resize(Size, -1);
9645   for (int i = 0; i < Size; ++i)
9646     if (Mask[i] >= 0)
9647       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9648   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9649          "Must not introduce lane crosses at this point!");
9650
9651   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9652 }
9653
9654 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9655 /// given mask.
9656 ///
9657 /// This returns true if the elements from a particular input are already in the
9658 /// slot required by the given mask and require no permutation.
9659 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9660   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9661   int Size = Mask.size();
9662   for (int i = 0; i < Size; ++i)
9663     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9664       return false;
9665
9666   return true;
9667 }
9668
9669 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9670                                             ArrayRef<int> Mask, SDValue V1,
9671                                             SDValue V2, SelectionDAG &DAG) {
9672
9673   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9674   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9675   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9676   int NumElts = VT.getVectorNumElements();
9677   bool ShufpdMask = true;
9678   bool CommutableMask = true;
9679   unsigned Immediate = 0;
9680   for (int i = 0; i < NumElts; ++i) {
9681     if (Mask[i] < 0)
9682       continue;
9683     int Val = (i & 6) + NumElts * (i & 1);
9684     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9685     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9686       ShufpdMask = false;
9687     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9688       CommutableMask = false;
9689     Immediate |= (Mask[i] % 2) << i;
9690   }
9691   if (ShufpdMask)
9692     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9693                        DAG.getConstant(Immediate, DL, MVT::i8));
9694   if (CommutableMask)
9695     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9696                        DAG.getConstant(Immediate, DL, MVT::i8));
9697   return SDValue();
9698 }
9699
9700 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9701 ///
9702 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9703 /// isn't available.
9704 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9705                                        const X86Subtarget *Subtarget,
9706                                        SelectionDAG &DAG) {
9707   SDLoc DL(Op);
9708   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9709   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9710   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9711   ArrayRef<int> Mask = SVOp->getMask();
9712   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9713
9714   SmallVector<int, 4> WidenedMask;
9715   if (canWidenShuffleElements(Mask, WidenedMask))
9716     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9717                                     DAG);
9718
9719   if (isSingleInputShuffleMask(Mask)) {
9720     // Check for being able to broadcast a single element.
9721     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9722                                                           Mask, Subtarget, DAG))
9723       return Broadcast;
9724
9725     // Use low duplicate instructions for masks that match their pattern.
9726     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9727       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9728
9729     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9730       // Non-half-crossing single input shuffles can be lowerid with an
9731       // interleaved permutation.
9732       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9733                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9734       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9735                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9736     }
9737
9738     // With AVX2 we have direct support for this permutation.
9739     if (Subtarget->hasAVX2())
9740       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9741                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9742
9743     // Otherwise, fall back.
9744     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9745                                                    DAG);
9746   }
9747
9748   // X86 has dedicated unpack instructions that can handle specific blend
9749   // operations: UNPCKH and UNPCKL.
9750   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9751     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9752   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9753     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9754   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9755     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9756   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9757     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9758
9759   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9760                                                 Subtarget, DAG))
9761     return Blend;
9762
9763   // Check if the blend happens to exactly fit that of SHUFPD.
9764   if (SDValue Op =
9765       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9766     return Op;
9767
9768   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9769   // shuffle. However, if we have AVX2 and either inputs are already in place,
9770   // we will be able to shuffle even across lanes the other input in a single
9771   // instruction so skip this pattern.
9772   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9773                                  isShuffleMaskInputInPlace(1, Mask))))
9774     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9775             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9776       return Result;
9777
9778   // If we have AVX2 then we always want to lower with a blend because an v4 we
9779   // can fully permute the elements.
9780   if (Subtarget->hasAVX2())
9781     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9782                                                       Mask, DAG);
9783
9784   // Otherwise fall back on generic lowering.
9785   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9786 }
9787
9788 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9789 ///
9790 /// This routine is only called when we have AVX2 and thus a reasonable
9791 /// instruction set for v4i64 shuffling..
9792 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9793                                        const X86Subtarget *Subtarget,
9794                                        SelectionDAG &DAG) {
9795   SDLoc DL(Op);
9796   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9797   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9798   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9799   ArrayRef<int> Mask = SVOp->getMask();
9800   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9801   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9802
9803   SmallVector<int, 4> WidenedMask;
9804   if (canWidenShuffleElements(Mask, WidenedMask))
9805     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9806                                     DAG);
9807
9808   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9809                                                 Subtarget, DAG))
9810     return Blend;
9811
9812   // Check for being able to broadcast a single element.
9813   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9814                                                         Mask, Subtarget, DAG))
9815     return Broadcast;
9816
9817   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9818   // use lower latency instructions that will operate on both 128-bit lanes.
9819   SmallVector<int, 2> RepeatedMask;
9820   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9821     if (isSingleInputShuffleMask(Mask)) {
9822       int PSHUFDMask[] = {-1, -1, -1, -1};
9823       for (int i = 0; i < 2; ++i)
9824         if (RepeatedMask[i] >= 0) {
9825           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9826           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9827         }
9828       return DAG.getBitcast(
9829           MVT::v4i64,
9830           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9831                       DAG.getBitcast(MVT::v8i32, V1),
9832                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9833     }
9834   }
9835
9836   // AVX2 provides a direct instruction for permuting a single input across
9837   // lanes.
9838   if (isSingleInputShuffleMask(Mask))
9839     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9840                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9841
9842   // Try to use shift instructions.
9843   if (SDValue Shift =
9844           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9845     return Shift;
9846
9847   // Use dedicated unpack instructions for masks that match their pattern.
9848   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9849     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9850   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9851     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9852   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9853     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9854   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9855     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9856
9857   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9858   // shuffle. However, if we have AVX2 and either inputs are already in place,
9859   // we will be able to shuffle even across lanes the other input in a single
9860   // instruction so skip this pattern.
9861   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9862                                  isShuffleMaskInputInPlace(1, Mask))))
9863     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9864             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9865       return Result;
9866
9867   // Otherwise fall back on generic blend lowering.
9868   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9869                                                     Mask, DAG);
9870 }
9871
9872 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9873 ///
9874 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9875 /// isn't available.
9876 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9877                                        const X86Subtarget *Subtarget,
9878                                        SelectionDAG &DAG) {
9879   SDLoc DL(Op);
9880   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9881   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9882   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9883   ArrayRef<int> Mask = SVOp->getMask();
9884   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9885
9886   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9887                                                 Subtarget, DAG))
9888     return Blend;
9889
9890   // Check for being able to broadcast a single element.
9891   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9892                                                         Mask, Subtarget, DAG))
9893     return Broadcast;
9894
9895   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9896   // options to efficiently lower the shuffle.
9897   SmallVector<int, 4> RepeatedMask;
9898   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9899     assert(RepeatedMask.size() == 4 &&
9900            "Repeated masks must be half the mask width!");
9901
9902     // Use even/odd duplicate instructions for masks that match their pattern.
9903     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9904       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9905     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9906       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9907
9908     if (isSingleInputShuffleMask(Mask))
9909       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9910                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9911
9912     // Use dedicated unpack instructions for masks that match their pattern.
9913     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9914       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9915     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9916       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9917     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9918       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9919     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9920       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9921
9922     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9923     // have already handled any direct blends. We also need to squash the
9924     // repeated mask into a simulated v4f32 mask.
9925     for (int i = 0; i < 4; ++i)
9926       if (RepeatedMask[i] >= 8)
9927         RepeatedMask[i] -= 4;
9928     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9929   }
9930
9931   // If we have a single input shuffle with different shuffle patterns in the
9932   // two 128-bit lanes use the variable mask to VPERMILPS.
9933   if (isSingleInputShuffleMask(Mask)) {
9934     SDValue VPermMask[8];
9935     for (int i = 0; i < 8; ++i)
9936       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9937                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9938     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9939       return DAG.getNode(
9940           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9941           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9942
9943     if (Subtarget->hasAVX2())
9944       return DAG.getNode(
9945           X86ISD::VPERMV, DL, MVT::v8f32,
9946           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
9947                                                  MVT::v8i32, VPermMask)),
9948           V1);
9949
9950     // Otherwise, fall back.
9951     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9952                                                    DAG);
9953   }
9954
9955   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9956   // shuffle.
9957   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9958           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9959     return Result;
9960
9961   // If we have AVX2 then we always want to lower with a blend because at v8 we
9962   // can fully permute the elements.
9963   if (Subtarget->hasAVX2())
9964     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9965                                                       Mask, DAG);
9966
9967   // Otherwise fall back on generic lowering.
9968   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9969 }
9970
9971 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9972 ///
9973 /// This routine is only called when we have AVX2 and thus a reasonable
9974 /// instruction set for v8i32 shuffling..
9975 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9976                                        const X86Subtarget *Subtarget,
9977                                        SelectionDAG &DAG) {
9978   SDLoc DL(Op);
9979   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9980   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9981   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9982   ArrayRef<int> Mask = SVOp->getMask();
9983   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9984   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9985
9986   // Whenever we can lower this as a zext, that instruction is strictly faster
9987   // than any alternative. It also allows us to fold memory operands into the
9988   // shuffle in many cases.
9989   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9990                                                          Mask, Subtarget, DAG))
9991     return ZExt;
9992
9993   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9994                                                 Subtarget, DAG))
9995     return Blend;
9996
9997   // Check for being able to broadcast a single element.
9998   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9999                                                         Mask, Subtarget, DAG))
10000     return Broadcast;
10001
10002   // If the shuffle mask is repeated in each 128-bit lane we can use more
10003   // efficient instructions that mirror the shuffles across the two 128-bit
10004   // lanes.
10005   SmallVector<int, 4> RepeatedMask;
10006   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10007     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10008     if (isSingleInputShuffleMask(Mask))
10009       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10010                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10011
10012     // Use dedicated unpack instructions for masks that match their pattern.
10013     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10014       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10015     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10016       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10017     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10018       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10019     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10020       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10021   }
10022
10023   // Try to use shift instructions.
10024   if (SDValue Shift =
10025           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10026     return Shift;
10027
10028   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10029           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10030     return Rotate;
10031
10032   // If the shuffle patterns aren't repeated but it is a single input, directly
10033   // generate a cross-lane VPERMD instruction.
10034   if (isSingleInputShuffleMask(Mask)) {
10035     SDValue VPermMask[8];
10036     for (int i = 0; i < 8; ++i)
10037       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10038                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10039     return DAG.getNode(
10040         X86ISD::VPERMV, DL, MVT::v8i32,
10041         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10042   }
10043
10044   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10045   // shuffle.
10046   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10047           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10048     return Result;
10049
10050   // Otherwise fall back on generic blend lowering.
10051   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10052                                                     Mask, DAG);
10053 }
10054
10055 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10056 ///
10057 /// This routine is only called when we have AVX2 and thus a reasonable
10058 /// instruction set for v16i16 shuffling..
10059 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10060                                         const X86Subtarget *Subtarget,
10061                                         SelectionDAG &DAG) {
10062   SDLoc DL(Op);
10063   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10064   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10065   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10066   ArrayRef<int> Mask = SVOp->getMask();
10067   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10068   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10069
10070   // Whenever we can lower this as a zext, that instruction is strictly faster
10071   // than any alternative. It also allows us to fold memory operands into the
10072   // shuffle in many cases.
10073   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10074                                                          Mask, Subtarget, DAG))
10075     return ZExt;
10076
10077   // Check for being able to broadcast a single element.
10078   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10079                                                         Mask, Subtarget, DAG))
10080     return Broadcast;
10081
10082   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10083                                                 Subtarget, DAG))
10084     return Blend;
10085
10086   // Use dedicated unpack instructions for masks that match their pattern.
10087   if (isShuffleEquivalent(V1, V2, Mask,
10088                           {// First 128-bit lane:
10089                            0, 16, 1, 17, 2, 18, 3, 19,
10090                            // Second 128-bit lane:
10091                            8, 24, 9, 25, 10, 26, 11, 27}))
10092     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10093   if (isShuffleEquivalent(V1, V2, Mask,
10094                           {// First 128-bit lane:
10095                            4, 20, 5, 21, 6, 22, 7, 23,
10096                            // Second 128-bit lane:
10097                            12, 28, 13, 29, 14, 30, 15, 31}))
10098     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10099
10100   // Try to use shift instructions.
10101   if (SDValue Shift =
10102           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10103     return Shift;
10104
10105   // Try to use byte rotation instructions.
10106   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10107           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10108     return Rotate;
10109
10110   if (isSingleInputShuffleMask(Mask)) {
10111     // There are no generalized cross-lane shuffle operations available on i16
10112     // element types.
10113     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10114       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10115                                                      Mask, DAG);
10116
10117     SmallVector<int, 8> RepeatedMask;
10118     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10119       // As this is a single-input shuffle, the repeated mask should be
10120       // a strictly valid v8i16 mask that we can pass through to the v8i16
10121       // lowering to handle even the v16 case.
10122       return lowerV8I16GeneralSingleInputVectorShuffle(
10123           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10124     }
10125
10126     SDValue PSHUFBMask[32];
10127     for (int i = 0; i < 16; ++i) {
10128       if (Mask[i] == -1) {
10129         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10130         continue;
10131       }
10132
10133       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10134       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10135       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10136       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10137     }
10138     return DAG.getBitcast(MVT::v16i16,
10139                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10140                                       DAG.getBitcast(MVT::v32i8, V1),
10141                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10142                                                   MVT::v32i8, PSHUFBMask)));
10143   }
10144
10145   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10146   // shuffle.
10147   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10148           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10149     return Result;
10150
10151   // Otherwise fall back on generic lowering.
10152   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10153 }
10154
10155 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10156 ///
10157 /// This routine is only called when we have AVX2 and thus a reasonable
10158 /// instruction set for v32i8 shuffling..
10159 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10160                                        const X86Subtarget *Subtarget,
10161                                        SelectionDAG &DAG) {
10162   SDLoc DL(Op);
10163   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10164   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10165   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10166   ArrayRef<int> Mask = SVOp->getMask();
10167   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10168   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10169
10170   // Whenever we can lower this as a zext, that instruction is strictly faster
10171   // than any alternative. It also allows us to fold memory operands into the
10172   // shuffle in many cases.
10173   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10174                                                          Mask, Subtarget, DAG))
10175     return ZExt;
10176
10177   // Check for being able to broadcast a single element.
10178   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10179                                                         Mask, Subtarget, DAG))
10180     return Broadcast;
10181
10182   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10183                                                 Subtarget, DAG))
10184     return Blend;
10185
10186   // Use dedicated unpack instructions for masks that match their pattern.
10187   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10188   // 256-bit lanes.
10189   if (isShuffleEquivalent(
10190           V1, V2, Mask,
10191           {// First 128-bit lane:
10192            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10193            // Second 128-bit lane:
10194            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10195     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10196   if (isShuffleEquivalent(
10197           V1, V2, Mask,
10198           {// First 128-bit lane:
10199            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10200            // Second 128-bit lane:
10201            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10202     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10203
10204   // Try to use shift instructions.
10205   if (SDValue Shift =
10206           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10207     return Shift;
10208
10209   // Try to use byte rotation instructions.
10210   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10211           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10212     return Rotate;
10213
10214   if (isSingleInputShuffleMask(Mask)) {
10215     // There are no generalized cross-lane shuffle operations available on i8
10216     // element types.
10217     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10218       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10219                                                      Mask, DAG);
10220
10221     SDValue PSHUFBMask[32];
10222     for (int i = 0; i < 32; ++i)
10223       PSHUFBMask[i] =
10224           Mask[i] < 0
10225               ? DAG.getUNDEF(MVT::i8)
10226               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10227                                 MVT::i8);
10228
10229     return DAG.getNode(
10230         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10231         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10232   }
10233
10234   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10235   // shuffle.
10236   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10237           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10238     return Result;
10239
10240   // Otherwise fall back on generic lowering.
10241   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10242 }
10243
10244 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10245 ///
10246 /// This routine either breaks down the specific type of a 256-bit x86 vector
10247 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10248 /// together based on the available instructions.
10249 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10250                                         MVT VT, const X86Subtarget *Subtarget,
10251                                         SelectionDAG &DAG) {
10252   SDLoc DL(Op);
10253   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10254   ArrayRef<int> Mask = SVOp->getMask();
10255
10256   // If we have a single input to the zero element, insert that into V1 if we
10257   // can do so cheaply.
10258   int NumElts = VT.getVectorNumElements();
10259   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10260     return M >= NumElts;
10261   });
10262
10263   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10264     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10265                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10266       return Insertion;
10267
10268   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10269   // check for those subtargets here and avoid much of the subtarget querying in
10270   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10271   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10272   // floating point types there eventually, just immediately cast everything to
10273   // a float and operate entirely in that domain.
10274   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10275     int ElementBits = VT.getScalarSizeInBits();
10276     if (ElementBits < 32)
10277       // No floating point type available, decompose into 128-bit vectors.
10278       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10279
10280     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10281                                 VT.getVectorNumElements());
10282     V1 = DAG.getBitcast(FpVT, V1);
10283     V2 = DAG.getBitcast(FpVT, V2);
10284     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10285   }
10286
10287   switch (VT.SimpleTy) {
10288   case MVT::v4f64:
10289     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10290   case MVT::v4i64:
10291     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10292   case MVT::v8f32:
10293     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10294   case MVT::v8i32:
10295     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10296   case MVT::v16i16:
10297     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10298   case MVT::v32i8:
10299     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10300
10301   default:
10302     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10303   }
10304 }
10305
10306 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10307 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10308                                        const X86Subtarget *Subtarget,
10309                                        SelectionDAG &DAG) {
10310   SDLoc DL(Op);
10311   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10312   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10313   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10314   ArrayRef<int> Mask = SVOp->getMask();
10315   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10316
10317   // X86 has dedicated unpack instructions that can handle specific blend
10318   // operations: UNPCKH and UNPCKL.
10319   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10320     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10321   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10322     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10323
10324   // FIXME: Implement direct support for this type!
10325   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10326 }
10327
10328 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10329 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10330                                        const X86Subtarget *Subtarget,
10331                                        SelectionDAG &DAG) {
10332   SDLoc DL(Op);
10333   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10334   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10335   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10336   ArrayRef<int> Mask = SVOp->getMask();
10337   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10338
10339   // Use dedicated unpack instructions for masks that match their pattern.
10340   if (isShuffleEquivalent(V1, V2, Mask,
10341                           {// First 128-bit lane.
10342                            0, 16, 1, 17, 4, 20, 5, 21,
10343                            // Second 128-bit lane.
10344                            8, 24, 9, 25, 12, 28, 13, 29}))
10345     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10346   if (isShuffleEquivalent(V1, V2, Mask,
10347                           {// First 128-bit lane.
10348                            2, 18, 3, 19, 6, 22, 7, 23,
10349                            // Second 128-bit lane.
10350                            10, 26, 11, 27, 14, 30, 15, 31}))
10351     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10352
10353   // FIXME: Implement direct support for this type!
10354   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10355 }
10356
10357 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10358 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10359                                        const X86Subtarget *Subtarget,
10360                                        SelectionDAG &DAG) {
10361   SDLoc DL(Op);
10362   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10363   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10364   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10365   ArrayRef<int> Mask = SVOp->getMask();
10366   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10367
10368   // X86 has dedicated unpack instructions that can handle specific blend
10369   // operations: UNPCKH and UNPCKL.
10370   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10371     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10372   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10373     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10374
10375   // FIXME: Implement direct support for this type!
10376   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10377 }
10378
10379 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10380 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10381                                        const X86Subtarget *Subtarget,
10382                                        SelectionDAG &DAG) {
10383   SDLoc DL(Op);
10384   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10385   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10386   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10387   ArrayRef<int> Mask = SVOp->getMask();
10388   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10389
10390   // Use dedicated unpack instructions for masks that match their pattern.
10391   if (isShuffleEquivalent(V1, V2, Mask,
10392                           {// First 128-bit lane.
10393                            0, 16, 1, 17, 4, 20, 5, 21,
10394                            // Second 128-bit lane.
10395                            8, 24, 9, 25, 12, 28, 13, 29}))
10396     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10397   if (isShuffleEquivalent(V1, V2, Mask,
10398                           {// First 128-bit lane.
10399                            2, 18, 3, 19, 6, 22, 7, 23,
10400                            // Second 128-bit lane.
10401                            10, 26, 11, 27, 14, 30, 15, 31}))
10402     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10403
10404   // FIXME: Implement direct support for this type!
10405   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10406 }
10407
10408 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10409 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10410                                         const X86Subtarget *Subtarget,
10411                                         SelectionDAG &DAG) {
10412   SDLoc DL(Op);
10413   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10414   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10415   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10416   ArrayRef<int> Mask = SVOp->getMask();
10417   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10418   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10419
10420   // FIXME: Implement direct support for this type!
10421   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10422 }
10423
10424 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10425 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10426                                        const X86Subtarget *Subtarget,
10427                                        SelectionDAG &DAG) {
10428   SDLoc DL(Op);
10429   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10430   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10431   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10432   ArrayRef<int> Mask = SVOp->getMask();
10433   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10434   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10435
10436   // FIXME: Implement direct support for this type!
10437   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10438 }
10439
10440 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10441 ///
10442 /// This routine either breaks down the specific type of a 512-bit x86 vector
10443 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10444 /// together based on the available instructions.
10445 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10446                                         MVT VT, const X86Subtarget *Subtarget,
10447                                         SelectionDAG &DAG) {
10448   SDLoc DL(Op);
10449   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10450   ArrayRef<int> Mask = SVOp->getMask();
10451   assert(Subtarget->hasAVX512() &&
10452          "Cannot lower 512-bit vectors w/ basic ISA!");
10453
10454   // Check for being able to broadcast a single element.
10455   if (SDValue Broadcast =
10456           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10457     return Broadcast;
10458
10459   // Dispatch to each element type for lowering. If we don't have supprot for
10460   // specific element type shuffles at 512 bits, immediately split them and
10461   // lower them. Each lowering routine of a given type is allowed to assume that
10462   // the requisite ISA extensions for that element type are available.
10463   switch (VT.SimpleTy) {
10464   case MVT::v8f64:
10465     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10466   case MVT::v16f32:
10467     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10468   case MVT::v8i64:
10469     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10470   case MVT::v16i32:
10471     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10472   case MVT::v32i16:
10473     if (Subtarget->hasBWI())
10474       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10475     break;
10476   case MVT::v64i8:
10477     if (Subtarget->hasBWI())
10478       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10479     break;
10480
10481   default:
10482     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10483   }
10484
10485   // Otherwise fall back on splitting.
10486   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10487 }
10488
10489 /// \brief Top-level lowering for x86 vector shuffles.
10490 ///
10491 /// This handles decomposition, canonicalization, and lowering of all x86
10492 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10493 /// above in helper routines. The canonicalization attempts to widen shuffles
10494 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10495 /// s.t. only one of the two inputs needs to be tested, etc.
10496 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10497                                   SelectionDAG &DAG) {
10498   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10499   ArrayRef<int> Mask = SVOp->getMask();
10500   SDValue V1 = Op.getOperand(0);
10501   SDValue V2 = Op.getOperand(1);
10502   MVT VT = Op.getSimpleValueType();
10503   int NumElements = VT.getVectorNumElements();
10504   SDLoc dl(Op);
10505
10506   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10507
10508   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10509   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10510   if (V1IsUndef && V2IsUndef)
10511     return DAG.getUNDEF(VT);
10512
10513   // When we create a shuffle node we put the UNDEF node to second operand,
10514   // but in some cases the first operand may be transformed to UNDEF.
10515   // In this case we should just commute the node.
10516   if (V1IsUndef)
10517     return DAG.getCommutedVectorShuffle(*SVOp);
10518
10519   // Check for non-undef masks pointing at an undef vector and make the masks
10520   // undef as well. This makes it easier to match the shuffle based solely on
10521   // the mask.
10522   if (V2IsUndef)
10523     for (int M : Mask)
10524       if (M >= NumElements) {
10525         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10526         for (int &M : NewMask)
10527           if (M >= NumElements)
10528             M = -1;
10529         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10530       }
10531
10532   // We actually see shuffles that are entirely re-arrangements of a set of
10533   // zero inputs. This mostly happens while decomposing complex shuffles into
10534   // simple ones. Directly lower these as a buildvector of zeros.
10535   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10536   if (Zeroable.all())
10537     return getZeroVector(VT, Subtarget, DAG, dl);
10538
10539   // Try to collapse shuffles into using a vector type with fewer elements but
10540   // wider element types. We cap this to not form integers or floating point
10541   // elements wider than 64 bits, but it might be interesting to form i128
10542   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10543   SmallVector<int, 16> WidenedMask;
10544   if (VT.getScalarSizeInBits() < 64 &&
10545       canWidenShuffleElements(Mask, WidenedMask)) {
10546     MVT NewEltVT = VT.isFloatingPoint()
10547                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10548                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10549     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10550     // Make sure that the new vector type is legal. For example, v2f64 isn't
10551     // legal on SSE1.
10552     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10553       V1 = DAG.getBitcast(NewVT, V1);
10554       V2 = DAG.getBitcast(NewVT, V2);
10555       return DAG.getBitcast(
10556           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10557     }
10558   }
10559
10560   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10561   for (int M : SVOp->getMask())
10562     if (M < 0)
10563       ++NumUndefElements;
10564     else if (M < NumElements)
10565       ++NumV1Elements;
10566     else
10567       ++NumV2Elements;
10568
10569   // Commute the shuffle as needed such that more elements come from V1 than
10570   // V2. This allows us to match the shuffle pattern strictly on how many
10571   // elements come from V1 without handling the symmetric cases.
10572   if (NumV2Elements > NumV1Elements)
10573     return DAG.getCommutedVectorShuffle(*SVOp);
10574
10575   // When the number of V1 and V2 elements are the same, try to minimize the
10576   // number of uses of V2 in the low half of the vector. When that is tied,
10577   // ensure that the sum of indices for V1 is equal to or lower than the sum
10578   // indices for V2. When those are equal, try to ensure that the number of odd
10579   // indices for V1 is lower than the number of odd indices for V2.
10580   if (NumV1Elements == NumV2Elements) {
10581     int LowV1Elements = 0, LowV2Elements = 0;
10582     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10583       if (M >= NumElements)
10584         ++LowV2Elements;
10585       else if (M >= 0)
10586         ++LowV1Elements;
10587     if (LowV2Elements > LowV1Elements) {
10588       return DAG.getCommutedVectorShuffle(*SVOp);
10589     } else if (LowV2Elements == LowV1Elements) {
10590       int SumV1Indices = 0, SumV2Indices = 0;
10591       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10592         if (SVOp->getMask()[i] >= NumElements)
10593           SumV2Indices += i;
10594         else if (SVOp->getMask()[i] >= 0)
10595           SumV1Indices += i;
10596       if (SumV2Indices < SumV1Indices) {
10597         return DAG.getCommutedVectorShuffle(*SVOp);
10598       } else if (SumV2Indices == SumV1Indices) {
10599         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10600         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10601           if (SVOp->getMask()[i] >= NumElements)
10602             NumV2OddIndices += i % 2;
10603           else if (SVOp->getMask()[i] >= 0)
10604             NumV1OddIndices += i % 2;
10605         if (NumV2OddIndices < NumV1OddIndices)
10606           return DAG.getCommutedVectorShuffle(*SVOp);
10607       }
10608     }
10609   }
10610
10611   // For each vector width, delegate to a specialized lowering routine.
10612   if (VT.getSizeInBits() == 128)
10613     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10614
10615   if (VT.getSizeInBits() == 256)
10616     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10617
10618   // Force AVX-512 vectors to be scalarized for now.
10619   // FIXME: Implement AVX-512 support!
10620   if (VT.getSizeInBits() == 512)
10621     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10622
10623   llvm_unreachable("Unimplemented!");
10624 }
10625
10626 // This function assumes its argument is a BUILD_VECTOR of constants or
10627 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10628 // true.
10629 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10630                                     unsigned &MaskValue) {
10631   MaskValue = 0;
10632   unsigned NumElems = BuildVector->getNumOperands();
10633   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10634   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10635   unsigned NumElemsInLane = NumElems / NumLanes;
10636
10637   // Blend for v16i16 should be symetric for the both lanes.
10638   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10639     SDValue EltCond = BuildVector->getOperand(i);
10640     SDValue SndLaneEltCond =
10641         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10642
10643     int Lane1Cond = -1, Lane2Cond = -1;
10644     if (isa<ConstantSDNode>(EltCond))
10645       Lane1Cond = !isZero(EltCond);
10646     if (isa<ConstantSDNode>(SndLaneEltCond))
10647       Lane2Cond = !isZero(SndLaneEltCond);
10648
10649     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10650       // Lane1Cond != 0, means we want the first argument.
10651       // Lane1Cond == 0, means we want the second argument.
10652       // The encoding of this argument is 0 for the first argument, 1
10653       // for the second. Therefore, invert the condition.
10654       MaskValue |= !Lane1Cond << i;
10655     else if (Lane1Cond < 0)
10656       MaskValue |= !Lane2Cond << i;
10657     else
10658       return false;
10659   }
10660   return true;
10661 }
10662
10663 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10664 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10665                                            const X86Subtarget *Subtarget,
10666                                            SelectionDAG &DAG) {
10667   SDValue Cond = Op.getOperand(0);
10668   SDValue LHS = Op.getOperand(1);
10669   SDValue RHS = Op.getOperand(2);
10670   SDLoc dl(Op);
10671   MVT VT = Op.getSimpleValueType();
10672
10673   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10674     return SDValue();
10675   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10676
10677   // Only non-legal VSELECTs reach this lowering, convert those into generic
10678   // shuffles and re-use the shuffle lowering path for blends.
10679   SmallVector<int, 32> Mask;
10680   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10681     SDValue CondElt = CondBV->getOperand(i);
10682     Mask.push_back(
10683         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10684   }
10685   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10686 }
10687
10688 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10689   // A vselect where all conditions and data are constants can be optimized into
10690   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10691   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10692       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10693       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10694     return SDValue();
10695
10696   // Try to lower this to a blend-style vector shuffle. This can handle all
10697   // constant condition cases.
10698   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10699     return BlendOp;
10700
10701   // Variable blends are only legal from SSE4.1 onward.
10702   if (!Subtarget->hasSSE41())
10703     return SDValue();
10704
10705   // Only some types will be legal on some subtargets. If we can emit a legal
10706   // VSELECT-matching blend, return Op, and but if we need to expand, return
10707   // a null value.
10708   switch (Op.getSimpleValueType().SimpleTy) {
10709   default:
10710     // Most of the vector types have blends past SSE4.1.
10711     return Op;
10712
10713   case MVT::v32i8:
10714     // The byte blends for AVX vectors were introduced only in AVX2.
10715     if (Subtarget->hasAVX2())
10716       return Op;
10717
10718     return SDValue();
10719
10720   case MVT::v8i16:
10721   case MVT::v16i16:
10722     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10723     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10724       return Op;
10725
10726     // FIXME: We should custom lower this by fixing the condition and using i8
10727     // blends.
10728     return SDValue();
10729   }
10730 }
10731
10732 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10733   MVT VT = Op.getSimpleValueType();
10734   SDLoc dl(Op);
10735
10736   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10737     return SDValue();
10738
10739   if (VT.getSizeInBits() == 8) {
10740     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10741                                   Op.getOperand(0), Op.getOperand(1));
10742     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10743                                   DAG.getValueType(VT));
10744     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10745   }
10746
10747   if (VT.getSizeInBits() == 16) {
10748     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10749     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10750     if (Idx == 0)
10751       return DAG.getNode(
10752           ISD::TRUNCATE, dl, MVT::i16,
10753           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10754                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10755                       Op.getOperand(1)));
10756     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10757                                   Op.getOperand(0), Op.getOperand(1));
10758     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10759                                   DAG.getValueType(VT));
10760     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10761   }
10762
10763   if (VT == MVT::f32) {
10764     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10765     // the result back to FR32 register. It's only worth matching if the
10766     // result has a single use which is a store or a bitcast to i32.  And in
10767     // the case of a store, it's not worth it if the index is a constant 0,
10768     // because a MOVSSmr can be used instead, which is smaller and faster.
10769     if (!Op.hasOneUse())
10770       return SDValue();
10771     SDNode *User = *Op.getNode()->use_begin();
10772     if ((User->getOpcode() != ISD::STORE ||
10773          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10774           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10775         (User->getOpcode() != ISD::BITCAST ||
10776          User->getValueType(0) != MVT::i32))
10777       return SDValue();
10778     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10779                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10780                                   Op.getOperand(1));
10781     return DAG.getBitcast(MVT::f32, Extract);
10782   }
10783
10784   if (VT == MVT::i32 || VT == MVT::i64) {
10785     // ExtractPS/pextrq works with constant index.
10786     if (isa<ConstantSDNode>(Op.getOperand(1)))
10787       return Op;
10788   }
10789   return SDValue();
10790 }
10791
10792 /// Extract one bit from mask vector, like v16i1 or v8i1.
10793 /// AVX-512 feature.
10794 SDValue
10795 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10796   SDValue Vec = Op.getOperand(0);
10797   SDLoc dl(Vec);
10798   MVT VecVT = Vec.getSimpleValueType();
10799   SDValue Idx = Op.getOperand(1);
10800   MVT EltVT = Op.getSimpleValueType();
10801
10802   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10803   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10804          "Unexpected vector type in ExtractBitFromMaskVector");
10805
10806   // variable index can't be handled in mask registers,
10807   // extend vector to VR512
10808   if (!isa<ConstantSDNode>(Idx)) {
10809     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10810     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10811     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10812                               ExtVT.getVectorElementType(), Ext, Idx);
10813     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10814   }
10815
10816   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10817   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10818   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10819     rc = getRegClassFor(MVT::v16i1);
10820   unsigned MaxSift = rc->getSize()*8 - 1;
10821   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10822                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10823   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10824                     DAG.getConstant(MaxSift, dl, MVT::i8));
10825   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10826                        DAG.getIntPtrConstant(0, dl));
10827 }
10828
10829 SDValue
10830 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10831                                            SelectionDAG &DAG) const {
10832   SDLoc dl(Op);
10833   SDValue Vec = Op.getOperand(0);
10834   MVT VecVT = Vec.getSimpleValueType();
10835   SDValue Idx = Op.getOperand(1);
10836
10837   if (Op.getSimpleValueType() == MVT::i1)
10838     return ExtractBitFromMaskVector(Op, DAG);
10839
10840   if (!isa<ConstantSDNode>(Idx)) {
10841     if (VecVT.is512BitVector() ||
10842         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10843          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10844
10845       MVT MaskEltVT =
10846         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10847       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10848                                     MaskEltVT.getSizeInBits());
10849
10850       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10851       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10852                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10853                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10854       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10855       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10856                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10857     }
10858     return SDValue();
10859   }
10860
10861   // If this is a 256-bit vector result, first extract the 128-bit vector and
10862   // then extract the element from the 128-bit vector.
10863   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10864
10865     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10866     // Get the 128-bit vector.
10867     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10868     MVT EltVT = VecVT.getVectorElementType();
10869
10870     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10871
10872     //if (IdxVal >= NumElems/2)
10873     //  IdxVal -= NumElems/2;
10874     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10875     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10876                        DAG.getConstant(IdxVal, dl, MVT::i32));
10877   }
10878
10879   assert(VecVT.is128BitVector() && "Unexpected vector length");
10880
10881   if (Subtarget->hasSSE41())
10882     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10883       return Res;
10884
10885   MVT VT = Op.getSimpleValueType();
10886   // TODO: handle v16i8.
10887   if (VT.getSizeInBits() == 16) {
10888     SDValue Vec = Op.getOperand(0);
10889     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10890     if (Idx == 0)
10891       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10892                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10893                                      DAG.getBitcast(MVT::v4i32, Vec),
10894                                      Op.getOperand(1)));
10895     // Transform it so it match pextrw which produces a 32-bit result.
10896     MVT EltVT = MVT::i32;
10897     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10898                                   Op.getOperand(0), Op.getOperand(1));
10899     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10900                                   DAG.getValueType(VT));
10901     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10902   }
10903
10904   if (VT.getSizeInBits() == 32) {
10905     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10906     if (Idx == 0)
10907       return Op;
10908
10909     // SHUFPS the element to the lowest double word, then movss.
10910     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10911     MVT VVT = Op.getOperand(0).getSimpleValueType();
10912     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10913                                        DAG.getUNDEF(VVT), Mask);
10914     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10915                        DAG.getIntPtrConstant(0, dl));
10916   }
10917
10918   if (VT.getSizeInBits() == 64) {
10919     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10920     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10921     //        to match extract_elt for f64.
10922     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10923     if (Idx == 0)
10924       return Op;
10925
10926     // UNPCKHPD the element to the lowest double word, then movsd.
10927     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10928     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10929     int Mask[2] = { 1, -1 };
10930     MVT VVT = Op.getOperand(0).getSimpleValueType();
10931     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10932                                        DAG.getUNDEF(VVT), Mask);
10933     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10934                        DAG.getIntPtrConstant(0, dl));
10935   }
10936
10937   return SDValue();
10938 }
10939
10940 /// Insert one bit to mask vector, like v16i1 or v8i1.
10941 /// AVX-512 feature.
10942 SDValue
10943 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10944   SDLoc dl(Op);
10945   SDValue Vec = Op.getOperand(0);
10946   SDValue Elt = Op.getOperand(1);
10947   SDValue Idx = Op.getOperand(2);
10948   MVT VecVT = Vec.getSimpleValueType();
10949
10950   if (!isa<ConstantSDNode>(Idx)) {
10951     // Non constant index. Extend source and destination,
10952     // insert element and then truncate the result.
10953     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10954     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10955     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10956       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10957       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10958     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10959   }
10960
10961   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10962   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10963   if (IdxVal)
10964     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10965                            DAG.getConstant(IdxVal, dl, MVT::i8));
10966   if (Vec.getOpcode() == ISD::UNDEF)
10967     return EltInVec;
10968   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10969 }
10970
10971 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10972                                                   SelectionDAG &DAG) const {
10973   MVT VT = Op.getSimpleValueType();
10974   MVT EltVT = VT.getVectorElementType();
10975
10976   if (EltVT == MVT::i1)
10977     return InsertBitToMaskVector(Op, DAG);
10978
10979   SDLoc dl(Op);
10980   SDValue N0 = Op.getOperand(0);
10981   SDValue N1 = Op.getOperand(1);
10982   SDValue N2 = Op.getOperand(2);
10983   if (!isa<ConstantSDNode>(N2))
10984     return SDValue();
10985   auto *N2C = cast<ConstantSDNode>(N2);
10986   unsigned IdxVal = N2C->getZExtValue();
10987
10988   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10989   // into that, and then insert the subvector back into the result.
10990   if (VT.is256BitVector() || VT.is512BitVector()) {
10991     // With a 256-bit vector, we can insert into the zero element efficiently
10992     // using a blend if we have AVX or AVX2 and the right data type.
10993     if (VT.is256BitVector() && IdxVal == 0) {
10994       // TODO: It is worthwhile to cast integer to floating point and back
10995       // and incur a domain crossing penalty if that's what we'll end up
10996       // doing anyway after extracting to a 128-bit vector.
10997       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10998           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10999         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11000         N2 = DAG.getIntPtrConstant(1, dl);
11001         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11002       }
11003     }
11004
11005     // Get the desired 128-bit vector chunk.
11006     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11007
11008     // Insert the element into the desired chunk.
11009     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11010     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11011
11012     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11013                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11014
11015     // Insert the changed part back into the bigger vector
11016     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11017   }
11018   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11019
11020   if (Subtarget->hasSSE41()) {
11021     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11022       unsigned Opc;
11023       if (VT == MVT::v8i16) {
11024         Opc = X86ISD::PINSRW;
11025       } else {
11026         assert(VT == MVT::v16i8);
11027         Opc = X86ISD::PINSRB;
11028       }
11029
11030       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11031       // argument.
11032       if (N1.getValueType() != MVT::i32)
11033         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11034       if (N2.getValueType() != MVT::i32)
11035         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11036       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11037     }
11038
11039     if (EltVT == MVT::f32) {
11040       // Bits [7:6] of the constant are the source select. This will always be
11041       //   zero here. The DAG Combiner may combine an extract_elt index into
11042       //   these bits. For example (insert (extract, 3), 2) could be matched by
11043       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11044       // Bits [5:4] of the constant are the destination select. This is the
11045       //   value of the incoming immediate.
11046       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11047       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11048
11049       const Function *F = DAG.getMachineFunction().getFunction();
11050       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11051       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11052         // If this is an insertion of 32-bits into the low 32-bits of
11053         // a vector, we prefer to generate a blend with immediate rather
11054         // than an insertps. Blends are simpler operations in hardware and so
11055         // will always have equal or better performance than insertps.
11056         // But if optimizing for size and there's a load folding opportunity,
11057         // generate insertps because blendps does not have a 32-bit memory
11058         // operand form.
11059         N2 = DAG.getIntPtrConstant(1, dl);
11060         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11061         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11062       }
11063       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11064       // Create this as a scalar to vector..
11065       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11066       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11067     }
11068
11069     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11070       // PINSR* works with constant index.
11071       return Op;
11072     }
11073   }
11074
11075   if (EltVT == MVT::i8)
11076     return SDValue();
11077
11078   if (EltVT.getSizeInBits() == 16) {
11079     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11080     // as its second argument.
11081     if (N1.getValueType() != MVT::i32)
11082       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11083     if (N2.getValueType() != MVT::i32)
11084       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11085     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11086   }
11087   return SDValue();
11088 }
11089
11090 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11091   SDLoc dl(Op);
11092   MVT OpVT = Op.getSimpleValueType();
11093
11094   // If this is a 256-bit vector result, first insert into a 128-bit
11095   // vector and then insert into the 256-bit vector.
11096   if (!OpVT.is128BitVector()) {
11097     // Insert into a 128-bit vector.
11098     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11099     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11100                                  OpVT.getVectorNumElements() / SizeFactor);
11101
11102     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11103
11104     // Insert the 128-bit vector.
11105     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11106   }
11107
11108   if (OpVT == MVT::v1i64 &&
11109       Op.getOperand(0).getValueType() == MVT::i64)
11110     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11111
11112   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11113   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11114   return DAG.getBitcast(
11115       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11116 }
11117
11118 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11119 // a simple subregister reference or explicit instructions to grab
11120 // upper bits of a vector.
11121 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11122                                       SelectionDAG &DAG) {
11123   SDLoc dl(Op);
11124   SDValue In =  Op.getOperand(0);
11125   SDValue Idx = Op.getOperand(1);
11126   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11127   MVT ResVT   = Op.getSimpleValueType();
11128   MVT InVT    = In.getSimpleValueType();
11129
11130   if (Subtarget->hasFp256()) {
11131     if (ResVT.is128BitVector() &&
11132         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11133         isa<ConstantSDNode>(Idx)) {
11134       return Extract128BitVector(In, IdxVal, DAG, dl);
11135     }
11136     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11137         isa<ConstantSDNode>(Idx)) {
11138       return Extract256BitVector(In, IdxVal, DAG, dl);
11139     }
11140   }
11141   return SDValue();
11142 }
11143
11144 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11145 // simple superregister reference or explicit instructions to insert
11146 // the upper bits of a vector.
11147 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11148                                      SelectionDAG &DAG) {
11149   if (!Subtarget->hasAVX())
11150     return SDValue();
11151
11152   SDLoc dl(Op);
11153   SDValue Vec = Op.getOperand(0);
11154   SDValue SubVec = Op.getOperand(1);
11155   SDValue Idx = Op.getOperand(2);
11156
11157   if (!isa<ConstantSDNode>(Idx))
11158     return SDValue();
11159
11160   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11161   MVT OpVT = Op.getSimpleValueType();
11162   MVT SubVecVT = SubVec.getSimpleValueType();
11163
11164   // Fold two 16-byte subvector loads into one 32-byte load:
11165   // (insert_subvector (insert_subvector undef, (load addr), 0),
11166   //                   (load addr + 16), Elts/2)
11167   // --> load32 addr
11168   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11169       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11170       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11171       !Subtarget->isUnalignedMem32Slow()) {
11172     SDValue SubVec2 = Vec.getOperand(1);
11173     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11174       if (Idx2->getZExtValue() == 0) {
11175         SDValue Ops[] = { SubVec2, SubVec };
11176         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11177           return Ld;
11178       }
11179     }
11180   }
11181
11182   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11183       SubVecVT.is128BitVector())
11184     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11185
11186   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11187     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11188
11189   if (OpVT.getVectorElementType() == MVT::i1) {
11190     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11191       return Op;
11192     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11193     SDValue Undef = DAG.getUNDEF(OpVT);
11194     unsigned NumElems = OpVT.getVectorNumElements();
11195     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11196
11197     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11198       // Zero upper bits of the Vec
11199       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11200       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11201
11202       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11203                                  SubVec, ZeroIdx);
11204       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11205       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11206     }
11207     if (IdxVal == 0) {
11208       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11209                                  SubVec, ZeroIdx);
11210       // Zero upper bits of the Vec2
11211       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11212       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11213       // Zero lower bits of the Vec
11214       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11215       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11216       // Merge them together
11217       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11218     }
11219   }
11220   return SDValue();
11221 }
11222
11223 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11224 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11225 // one of the above mentioned nodes. It has to be wrapped because otherwise
11226 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11227 // be used to form addressing mode. These wrapped nodes will be selected
11228 // into MOV32ri.
11229 SDValue
11230 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11231   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11232
11233   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11234   // global base reg.
11235   unsigned char OpFlag = 0;
11236   unsigned WrapperKind = X86ISD::Wrapper;
11237   CodeModel::Model M = DAG.getTarget().getCodeModel();
11238
11239   if (Subtarget->isPICStyleRIPRel() &&
11240       (M == CodeModel::Small || M == CodeModel::Kernel))
11241     WrapperKind = X86ISD::WrapperRIP;
11242   else if (Subtarget->isPICStyleGOT())
11243     OpFlag = X86II::MO_GOTOFF;
11244   else if (Subtarget->isPICStyleStubPIC())
11245     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11246
11247   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11248                                              CP->getAlignment(),
11249                                              CP->getOffset(), OpFlag);
11250   SDLoc DL(CP);
11251   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11252   // With PIC, the address is actually $g + Offset.
11253   if (OpFlag) {
11254     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11255                          DAG.getNode(X86ISD::GlobalBaseReg,
11256                                      SDLoc(), getPointerTy()),
11257                          Result);
11258   }
11259
11260   return Result;
11261 }
11262
11263 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11264   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11265
11266   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11267   // global base reg.
11268   unsigned char OpFlag = 0;
11269   unsigned WrapperKind = X86ISD::Wrapper;
11270   CodeModel::Model M = DAG.getTarget().getCodeModel();
11271
11272   if (Subtarget->isPICStyleRIPRel() &&
11273       (M == CodeModel::Small || M == CodeModel::Kernel))
11274     WrapperKind = X86ISD::WrapperRIP;
11275   else if (Subtarget->isPICStyleGOT())
11276     OpFlag = X86II::MO_GOTOFF;
11277   else if (Subtarget->isPICStyleStubPIC())
11278     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11279
11280   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11281                                           OpFlag);
11282   SDLoc DL(JT);
11283   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11284
11285   // With PIC, the address is actually $g + Offset.
11286   if (OpFlag)
11287     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11288                          DAG.getNode(X86ISD::GlobalBaseReg,
11289                                      SDLoc(), getPointerTy()),
11290                          Result);
11291
11292   return Result;
11293 }
11294
11295 SDValue
11296 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11297   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11298
11299   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11300   // global base reg.
11301   unsigned char OpFlag = 0;
11302   unsigned WrapperKind = X86ISD::Wrapper;
11303   CodeModel::Model M = DAG.getTarget().getCodeModel();
11304
11305   if (Subtarget->isPICStyleRIPRel() &&
11306       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11307     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11308       OpFlag = X86II::MO_GOTPCREL;
11309     WrapperKind = X86ISD::WrapperRIP;
11310   } else if (Subtarget->isPICStyleGOT()) {
11311     OpFlag = X86II::MO_GOT;
11312   } else if (Subtarget->isPICStyleStubPIC()) {
11313     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11314   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11315     OpFlag = X86II::MO_DARWIN_NONLAZY;
11316   }
11317
11318   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11319
11320   SDLoc DL(Op);
11321   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11322
11323   // With PIC, the address is actually $g + Offset.
11324   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11325       !Subtarget->is64Bit()) {
11326     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11327                          DAG.getNode(X86ISD::GlobalBaseReg,
11328                                      SDLoc(), getPointerTy()),
11329                          Result);
11330   }
11331
11332   // For symbols that require a load from a stub to get the address, emit the
11333   // load.
11334   if (isGlobalStubReference(OpFlag))
11335     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11336                          MachinePointerInfo::getGOT(), false, false, false, 0);
11337
11338   return Result;
11339 }
11340
11341 SDValue
11342 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11343   // Create the TargetBlockAddressAddress node.
11344   unsigned char OpFlags =
11345     Subtarget->ClassifyBlockAddressReference();
11346   CodeModel::Model M = DAG.getTarget().getCodeModel();
11347   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11348   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11349   SDLoc dl(Op);
11350   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11351                                              OpFlags);
11352
11353   if (Subtarget->isPICStyleRIPRel() &&
11354       (M == CodeModel::Small || M == CodeModel::Kernel))
11355     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11356   else
11357     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11358
11359   // With PIC, the address is actually $g + Offset.
11360   if (isGlobalRelativeToPICBase(OpFlags)) {
11361     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11362                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11363                          Result);
11364   }
11365
11366   return Result;
11367 }
11368
11369 SDValue
11370 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11371                                       int64_t Offset, SelectionDAG &DAG) const {
11372   // Create the TargetGlobalAddress node, folding in the constant
11373   // offset if it is legal.
11374   unsigned char OpFlags =
11375       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11376   CodeModel::Model M = DAG.getTarget().getCodeModel();
11377   SDValue Result;
11378   if (OpFlags == X86II::MO_NO_FLAG &&
11379       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11380     // A direct static reference to a global.
11381     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11382     Offset = 0;
11383   } else {
11384     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11385   }
11386
11387   if (Subtarget->isPICStyleRIPRel() &&
11388       (M == CodeModel::Small || M == CodeModel::Kernel))
11389     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11390   else
11391     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11392
11393   // With PIC, the address is actually $g + Offset.
11394   if (isGlobalRelativeToPICBase(OpFlags)) {
11395     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11396                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11397                          Result);
11398   }
11399
11400   // For globals that require a load from a stub to get the address, emit the
11401   // load.
11402   if (isGlobalStubReference(OpFlags))
11403     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11404                          MachinePointerInfo::getGOT(), false, false, false, 0);
11405
11406   // If there was a non-zero offset that we didn't fold, create an explicit
11407   // addition for it.
11408   if (Offset != 0)
11409     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11410                          DAG.getConstant(Offset, dl, getPointerTy()));
11411
11412   return Result;
11413 }
11414
11415 SDValue
11416 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11417   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11418   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11419   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11420 }
11421
11422 static SDValue
11423 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11424            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11425            unsigned char OperandFlags, bool LocalDynamic = false) {
11426   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11427   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11428   SDLoc dl(GA);
11429   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11430                                            GA->getValueType(0),
11431                                            GA->getOffset(),
11432                                            OperandFlags);
11433
11434   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11435                                            : X86ISD::TLSADDR;
11436
11437   if (InFlag) {
11438     SDValue Ops[] = { Chain,  TGA, *InFlag };
11439     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11440   } else {
11441     SDValue Ops[]  = { Chain, TGA };
11442     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11443   }
11444
11445   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11446   MFI->setAdjustsStack(true);
11447   MFI->setHasCalls(true);
11448
11449   SDValue Flag = Chain.getValue(1);
11450   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11451 }
11452
11453 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11454 static SDValue
11455 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11456                                 const EVT PtrVT) {
11457   SDValue InFlag;
11458   SDLoc dl(GA);  // ? function entry point might be better
11459   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11460                                    DAG.getNode(X86ISD::GlobalBaseReg,
11461                                                SDLoc(), PtrVT), InFlag);
11462   InFlag = Chain.getValue(1);
11463
11464   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11465 }
11466
11467 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11468 static SDValue
11469 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11470                                 const EVT PtrVT) {
11471   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11472                     X86::RAX, X86II::MO_TLSGD);
11473 }
11474
11475 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11476                                            SelectionDAG &DAG,
11477                                            const EVT PtrVT,
11478                                            bool is64Bit) {
11479   SDLoc dl(GA);
11480
11481   // Get the start address of the TLS block for this module.
11482   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11483       .getInfo<X86MachineFunctionInfo>();
11484   MFI->incNumLocalDynamicTLSAccesses();
11485
11486   SDValue Base;
11487   if (is64Bit) {
11488     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11489                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11490   } else {
11491     SDValue InFlag;
11492     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11493         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11494     InFlag = Chain.getValue(1);
11495     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11496                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11497   }
11498
11499   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11500   // of Base.
11501
11502   // Build x@dtpoff.
11503   unsigned char OperandFlags = X86II::MO_DTPOFF;
11504   unsigned WrapperKind = X86ISD::Wrapper;
11505   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11506                                            GA->getValueType(0),
11507                                            GA->getOffset(), OperandFlags);
11508   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11509
11510   // Add x@dtpoff with the base.
11511   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11512 }
11513
11514 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11515 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11516                                    const EVT PtrVT, TLSModel::Model model,
11517                                    bool is64Bit, bool isPIC) {
11518   SDLoc dl(GA);
11519
11520   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11521   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11522                                                          is64Bit ? 257 : 256));
11523
11524   SDValue ThreadPointer =
11525       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11526                   MachinePointerInfo(Ptr), false, false, false, 0);
11527
11528   unsigned char OperandFlags = 0;
11529   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11530   // initialexec.
11531   unsigned WrapperKind = X86ISD::Wrapper;
11532   if (model == TLSModel::LocalExec) {
11533     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11534   } else if (model == TLSModel::InitialExec) {
11535     if (is64Bit) {
11536       OperandFlags = X86II::MO_GOTTPOFF;
11537       WrapperKind = X86ISD::WrapperRIP;
11538     } else {
11539       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11540     }
11541   } else {
11542     llvm_unreachable("Unexpected model");
11543   }
11544
11545   // emit "addl x@ntpoff,%eax" (local exec)
11546   // or "addl x@indntpoff,%eax" (initial exec)
11547   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11548   SDValue TGA =
11549       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11550                                  GA->getOffset(), OperandFlags);
11551   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11552
11553   if (model == TLSModel::InitialExec) {
11554     if (isPIC && !is64Bit) {
11555       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11556                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11557                            Offset);
11558     }
11559
11560     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11561                          MachinePointerInfo::getGOT(), false, false, false, 0);
11562   }
11563
11564   // The address of the thread local variable is the add of the thread
11565   // pointer with the offset of the variable.
11566   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11567 }
11568
11569 SDValue
11570 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11571
11572   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11573   const GlobalValue *GV = GA->getGlobal();
11574
11575   if (Subtarget->isTargetELF()) {
11576     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11577     switch (model) {
11578       case TLSModel::GeneralDynamic:
11579         if (Subtarget->is64Bit())
11580           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11581         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11582       case TLSModel::LocalDynamic:
11583         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11584                                            Subtarget->is64Bit());
11585       case TLSModel::InitialExec:
11586       case TLSModel::LocalExec:
11587         return LowerToTLSExecModel(
11588             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11589             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11590     }
11591     llvm_unreachable("Unknown TLS model.");
11592   }
11593
11594   if (Subtarget->isTargetDarwin()) {
11595     // Darwin only has one model of TLS.  Lower to that.
11596     unsigned char OpFlag = 0;
11597     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11598                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11599
11600     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11601     // global base reg.
11602     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11603                  !Subtarget->is64Bit();
11604     if (PIC32)
11605       OpFlag = X86II::MO_TLVP_PIC_BASE;
11606     else
11607       OpFlag = X86II::MO_TLVP;
11608     SDLoc DL(Op);
11609     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11610                                                 GA->getValueType(0),
11611                                                 GA->getOffset(), OpFlag);
11612     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11613
11614     // With PIC32, the address is actually $g + Offset.
11615     if (PIC32)
11616       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11617                            DAG.getNode(X86ISD::GlobalBaseReg,
11618                                        SDLoc(), getPointerTy()),
11619                            Offset);
11620
11621     // Lowering the machine isd will make sure everything is in the right
11622     // location.
11623     SDValue Chain = DAG.getEntryNode();
11624     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11625     SDValue Args[] = { Chain, Offset };
11626     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11627
11628     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11629     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11630     MFI->setAdjustsStack(true);
11631
11632     // And our return value (tls address) is in the standard call return value
11633     // location.
11634     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11635     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11636                               Chain.getValue(1));
11637   }
11638
11639   if (Subtarget->isTargetKnownWindowsMSVC() ||
11640       Subtarget->isTargetWindowsGNU()) {
11641     // Just use the implicit TLS architecture
11642     // Need to generate someting similar to:
11643     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11644     //                                  ; from TEB
11645     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11646     //   mov     rcx, qword [rdx+rcx*8]
11647     //   mov     eax, .tls$:tlsvar
11648     //   [rax+rcx] contains the address
11649     // Windows 64bit: gs:0x58
11650     // Windows 32bit: fs:__tls_array
11651
11652     SDLoc dl(GA);
11653     SDValue Chain = DAG.getEntryNode();
11654
11655     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11656     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11657     // use its literal value of 0x2C.
11658     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11659                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11660                                                              256)
11661                                         : Type::getInt32PtrTy(*DAG.getContext(),
11662                                                               257));
11663
11664     SDValue TlsArray =
11665         Subtarget->is64Bit()
11666             ? DAG.getIntPtrConstant(0x58, dl)
11667             : (Subtarget->isTargetWindowsGNU()
11668                    ? DAG.getIntPtrConstant(0x2C, dl)
11669                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11670
11671     SDValue ThreadPointer =
11672         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11673                     MachinePointerInfo(Ptr), false, false, false, 0);
11674
11675     SDValue res;
11676     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11677       res = ThreadPointer;
11678     } else {
11679       // Load the _tls_index variable
11680       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11681       if (Subtarget->is64Bit())
11682         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11683                              MachinePointerInfo(), MVT::i32, false, false,
11684                              false, 0);
11685       else
11686         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11687                           false, false, false, 0);
11688
11689       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11690                                       getPointerTy());
11691       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11692
11693       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11694     }
11695
11696     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11697                       false, false, false, 0);
11698
11699     // Get the offset of start of .tls section
11700     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11701                                              GA->getValueType(0),
11702                                              GA->getOffset(), X86II::MO_SECREL);
11703     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11704
11705     // The address of the thread local variable is the add of the thread
11706     // pointer with the offset of the variable.
11707     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11708   }
11709
11710   llvm_unreachable("TLS not implemented for this target.");
11711 }
11712
11713 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11714 /// and take a 2 x i32 value to shift plus a shift amount.
11715 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11716   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11717   MVT VT = Op.getSimpleValueType();
11718   unsigned VTBits = VT.getSizeInBits();
11719   SDLoc dl(Op);
11720   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11721   SDValue ShOpLo = Op.getOperand(0);
11722   SDValue ShOpHi = Op.getOperand(1);
11723   SDValue ShAmt  = Op.getOperand(2);
11724   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11725   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11726   // during isel.
11727   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11728                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11729   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11730                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11731                        : DAG.getConstant(0, dl, VT);
11732
11733   SDValue Tmp2, Tmp3;
11734   if (Op.getOpcode() == ISD::SHL_PARTS) {
11735     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11736     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11737   } else {
11738     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11739     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11740   }
11741
11742   // If the shift amount is larger or equal than the width of a part we can't
11743   // rely on the results of shld/shrd. Insert a test and select the appropriate
11744   // values for large shift amounts.
11745   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11746                                 DAG.getConstant(VTBits, dl, MVT::i8));
11747   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11748                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11749
11750   SDValue Hi, Lo;
11751   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11752   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11753   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11754
11755   if (Op.getOpcode() == ISD::SHL_PARTS) {
11756     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11757     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11758   } else {
11759     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11760     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11761   }
11762
11763   SDValue Ops[2] = { Lo, Hi };
11764   return DAG.getMergeValues(Ops, dl);
11765 }
11766
11767 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11768                                            SelectionDAG &DAG) const {
11769   SDValue Src = Op.getOperand(0);
11770   MVT SrcVT = Src.getSimpleValueType();
11771   MVT VT = Op.getSimpleValueType();
11772   SDLoc dl(Op);
11773
11774   if (SrcVT.isVector()) {
11775     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11776       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11777                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11778                          DAG.getUNDEF(SrcVT)));
11779     }
11780     if (SrcVT.getVectorElementType() == MVT::i1) {
11781       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11782       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11783                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11784     }
11785     return SDValue();
11786   }
11787
11788   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11789          "Unknown SINT_TO_FP to lower!");
11790
11791   // These are really Legal; return the operand so the caller accepts it as
11792   // Legal.
11793   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11794     return Op;
11795   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11796       Subtarget->is64Bit()) {
11797     return Op;
11798   }
11799
11800   unsigned Size = SrcVT.getSizeInBits()/8;
11801   MachineFunction &MF = DAG.getMachineFunction();
11802   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11803   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11804   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11805                                StackSlot,
11806                                MachinePointerInfo::getFixedStack(SSFI),
11807                                false, false, 0);
11808   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11809 }
11810
11811 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11812                                      SDValue StackSlot,
11813                                      SelectionDAG &DAG) const {
11814   // Build the FILD
11815   SDLoc DL(Op);
11816   SDVTList Tys;
11817   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11818   if (useSSE)
11819     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11820   else
11821     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11822
11823   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11824
11825   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11826   MachineMemOperand *MMO;
11827   if (FI) {
11828     int SSFI = FI->getIndex();
11829     MMO =
11830       DAG.getMachineFunction()
11831       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11832                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11833   } else {
11834     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11835     StackSlot = StackSlot.getOperand(1);
11836   }
11837   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11838   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11839                                            X86ISD::FILD, DL,
11840                                            Tys, Ops, SrcVT, MMO);
11841
11842   if (useSSE) {
11843     Chain = Result.getValue(1);
11844     SDValue InFlag = Result.getValue(2);
11845
11846     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11847     // shouldn't be necessary except that RFP cannot be live across
11848     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11849     MachineFunction &MF = DAG.getMachineFunction();
11850     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11851     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11852     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11853     Tys = DAG.getVTList(MVT::Other);
11854     SDValue Ops[] = {
11855       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11856     };
11857     MachineMemOperand *MMO =
11858       DAG.getMachineFunction()
11859       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11860                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11861
11862     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11863                                     Ops, Op.getValueType(), MMO);
11864     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11865                          MachinePointerInfo::getFixedStack(SSFI),
11866                          false, false, false, 0);
11867   }
11868
11869   return Result;
11870 }
11871
11872 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11873 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11874                                                SelectionDAG &DAG) const {
11875   // This algorithm is not obvious. Here it is what we're trying to output:
11876   /*
11877      movq       %rax,  %xmm0
11878      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11879      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11880      #ifdef __SSE3__
11881        haddpd   %xmm0, %xmm0
11882      #else
11883        pshufd   $0x4e, %xmm0, %xmm1
11884        addpd    %xmm1, %xmm0
11885      #endif
11886   */
11887
11888   SDLoc dl(Op);
11889   LLVMContext *Context = DAG.getContext();
11890
11891   // Build some magic constants.
11892   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11893   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11894   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11895
11896   SmallVector<Constant*,2> CV1;
11897   CV1.push_back(
11898     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11899                                       APInt(64, 0x4330000000000000ULL))));
11900   CV1.push_back(
11901     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11902                                       APInt(64, 0x4530000000000000ULL))));
11903   Constant *C1 = ConstantVector::get(CV1);
11904   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11905
11906   // Load the 64-bit value into an XMM register.
11907   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11908                             Op.getOperand(0));
11909   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11910                               MachinePointerInfo::getConstantPool(),
11911                               false, false, false, 16);
11912   SDValue Unpck1 =
11913       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11914
11915   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11916                               MachinePointerInfo::getConstantPool(),
11917                               false, false, false, 16);
11918   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11919   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11920   SDValue Result;
11921
11922   if (Subtarget->hasSSE3()) {
11923     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11924     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11925   } else {
11926     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11927     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11928                                            S2F, 0x4E, DAG);
11929     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11930                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11931   }
11932
11933   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11934                      DAG.getIntPtrConstant(0, dl));
11935 }
11936
11937 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11938 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11939                                                SelectionDAG &DAG) const {
11940   SDLoc dl(Op);
11941   // FP constant to bias correct the final result.
11942   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11943                                    MVT::f64);
11944
11945   // Load the 32-bit value into an XMM register.
11946   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11947                              Op.getOperand(0));
11948
11949   // Zero out the upper parts of the register.
11950   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11951
11952   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11953                      DAG.getBitcast(MVT::v2f64, Load),
11954                      DAG.getIntPtrConstant(0, dl));
11955
11956   // Or the load with the bias.
11957   SDValue Or = DAG.getNode(
11958       ISD::OR, dl, MVT::v2i64,
11959       DAG.getBitcast(MVT::v2i64,
11960                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
11961       DAG.getBitcast(MVT::v2i64,
11962                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
11963   Or =
11964       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11965                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
11966
11967   // Subtract the bias.
11968   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11969
11970   // Handle final rounding.
11971   EVT DestVT = Op.getValueType();
11972
11973   if (DestVT.bitsLT(MVT::f64))
11974     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11975                        DAG.getIntPtrConstant(0, dl));
11976   if (DestVT.bitsGT(MVT::f64))
11977     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11978
11979   // Handle final rounding.
11980   return Sub;
11981 }
11982
11983 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11984                                      const X86Subtarget &Subtarget) {
11985   // The algorithm is the following:
11986   // #ifdef __SSE4_1__
11987   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11988   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11989   //                                 (uint4) 0x53000000, 0xaa);
11990   // #else
11991   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11992   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11993   // #endif
11994   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11995   //     return (float4) lo + fhi;
11996
11997   SDLoc DL(Op);
11998   SDValue V = Op->getOperand(0);
11999   EVT VecIntVT = V.getValueType();
12000   bool Is128 = VecIntVT == MVT::v4i32;
12001   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12002   // If we convert to something else than the supported type, e.g., to v4f64,
12003   // abort early.
12004   if (VecFloatVT != Op->getValueType(0))
12005     return SDValue();
12006
12007   unsigned NumElts = VecIntVT.getVectorNumElements();
12008   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12009          "Unsupported custom type");
12010   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12011
12012   // In the #idef/#else code, we have in common:
12013   // - The vector of constants:
12014   // -- 0x4b000000
12015   // -- 0x53000000
12016   // - A shift:
12017   // -- v >> 16
12018
12019   // Create the splat vector for 0x4b000000.
12020   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12021   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12022                            CstLow, CstLow, CstLow, CstLow};
12023   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12024                                   makeArrayRef(&CstLowArray[0], NumElts));
12025   // Create the splat vector for 0x53000000.
12026   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12027   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12028                             CstHigh, CstHigh, CstHigh, CstHigh};
12029   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12030                                    makeArrayRef(&CstHighArray[0], NumElts));
12031
12032   // Create the right shift.
12033   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12034   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12035                              CstShift, CstShift, CstShift, CstShift};
12036   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12037                                     makeArrayRef(&CstShiftArray[0], NumElts));
12038   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12039
12040   SDValue Low, High;
12041   if (Subtarget.hasSSE41()) {
12042     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12043     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12044     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12045     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12046     // Low will be bitcasted right away, so do not bother bitcasting back to its
12047     // original type.
12048     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12049                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12050     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12051     //                                 (uint4) 0x53000000, 0xaa);
12052     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12053     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12054     // High will be bitcasted right away, so do not bother bitcasting back to
12055     // its original type.
12056     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12057                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12058   } else {
12059     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12060     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12061                                      CstMask, CstMask, CstMask);
12062     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12063     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12064     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12065
12066     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12067     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12068   }
12069
12070   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12071   SDValue CstFAdd = DAG.getConstantFP(
12072       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12073   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12074                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12075   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12076                                    makeArrayRef(&CstFAddArray[0], NumElts));
12077
12078   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12079   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12080   SDValue FHigh =
12081       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12082   //     return (float4) lo + fhi;
12083   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12084   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12085 }
12086
12087 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12088                                                SelectionDAG &DAG) const {
12089   SDValue N0 = Op.getOperand(0);
12090   MVT SVT = N0.getSimpleValueType();
12091   SDLoc dl(Op);
12092
12093   switch (SVT.SimpleTy) {
12094   default:
12095     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12096   case MVT::v4i8:
12097   case MVT::v4i16:
12098   case MVT::v8i8:
12099   case MVT::v8i16: {
12100     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12101     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12102                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12103   }
12104   case MVT::v4i32:
12105   case MVT::v8i32:
12106     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12107   case MVT::v16i8:
12108   case MVT::v16i16:
12109     if (Subtarget->hasAVX512())
12110       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12111                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12112   }
12113   llvm_unreachable(nullptr);
12114 }
12115
12116 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12117                                            SelectionDAG &DAG) const {
12118   SDValue N0 = Op.getOperand(0);
12119   SDLoc dl(Op);
12120
12121   if (Op.getValueType().isVector())
12122     return lowerUINT_TO_FP_vec(Op, DAG);
12123
12124   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12125   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12126   // the optimization here.
12127   if (DAG.SignBitIsZero(N0))
12128     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12129
12130   MVT SrcVT = N0.getSimpleValueType();
12131   MVT DstVT = Op.getSimpleValueType();
12132   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12133     return LowerUINT_TO_FP_i64(Op, DAG);
12134   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12135     return LowerUINT_TO_FP_i32(Op, DAG);
12136   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12137     return SDValue();
12138
12139   // Make a 64-bit buffer, and use it to build an FILD.
12140   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12141   if (SrcVT == MVT::i32) {
12142     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
12143     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
12144                                      getPointerTy(), StackSlot, WordOff);
12145     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12146                                   StackSlot, MachinePointerInfo(),
12147                                   false, false, 0);
12148     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12149                                   OffsetSlot, MachinePointerInfo(),
12150                                   false, false, 0);
12151     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12152     return Fild;
12153   }
12154
12155   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12156   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12157                                StackSlot, MachinePointerInfo(),
12158                                false, false, 0);
12159   // For i64 source, we need to add the appropriate power of 2 if the input
12160   // was negative.  This is the same as the optimization in
12161   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12162   // we must be careful to do the computation in x87 extended precision, not
12163   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12164   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12165   MachineMemOperand *MMO =
12166     DAG.getMachineFunction()
12167     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12168                           MachineMemOperand::MOLoad, 8, 8);
12169
12170   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12171   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12172   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12173                                          MVT::i64, MMO);
12174
12175   APInt FF(32, 0x5F800000ULL);
12176
12177   // Check whether the sign bit is set.
12178   SDValue SignSet = DAG.getSetCC(dl,
12179                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
12180                                  Op.getOperand(0),
12181                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12182
12183   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12184   SDValue FudgePtr = DAG.getConstantPool(
12185                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
12186                                          getPointerTy());
12187
12188   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12189   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12190   SDValue Four = DAG.getIntPtrConstant(4, dl);
12191   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12192                                Zero, Four);
12193   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
12194
12195   // Load the value out, extending it from f32 to f80.
12196   // FIXME: Avoid the extend by constructing the right constant pool?
12197   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12198                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12199                                  MVT::f32, false, false, false, 4);
12200   // Extend everything to 80 bits to force it to be done on x87.
12201   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12202   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12203                      DAG.getIntPtrConstant(0, dl));
12204 }
12205
12206 std::pair<SDValue,SDValue>
12207 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12208                                     bool IsSigned, bool IsReplace) const {
12209   SDLoc DL(Op);
12210
12211   EVT DstTy = Op.getValueType();
12212
12213   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12214     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12215     DstTy = MVT::i64;
12216   }
12217
12218   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12219          DstTy.getSimpleVT() >= MVT::i16 &&
12220          "Unknown FP_TO_INT to lower!");
12221
12222   // These are really Legal.
12223   if (DstTy == MVT::i32 &&
12224       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12225     return std::make_pair(SDValue(), SDValue());
12226   if (Subtarget->is64Bit() &&
12227       DstTy == MVT::i64 &&
12228       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12229     return std::make_pair(SDValue(), SDValue());
12230
12231   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12232   // stack slot, or into the FTOL runtime function.
12233   MachineFunction &MF = DAG.getMachineFunction();
12234   unsigned MemSize = DstTy.getSizeInBits()/8;
12235   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12236   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12237
12238   unsigned Opc;
12239   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12240     Opc = X86ISD::WIN_FTOL;
12241   else
12242     switch (DstTy.getSimpleVT().SimpleTy) {
12243     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12244     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12245     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12246     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12247     }
12248
12249   SDValue Chain = DAG.getEntryNode();
12250   SDValue Value = Op.getOperand(0);
12251   EVT TheVT = Op.getOperand(0).getValueType();
12252   // FIXME This causes a redundant load/store if the SSE-class value is already
12253   // in memory, such as if it is on the callstack.
12254   if (isScalarFPTypeInSSEReg(TheVT)) {
12255     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12256     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12257                          MachinePointerInfo::getFixedStack(SSFI),
12258                          false, false, 0);
12259     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12260     SDValue Ops[] = {
12261       Chain, StackSlot, DAG.getValueType(TheVT)
12262     };
12263
12264     MachineMemOperand *MMO =
12265       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12266                               MachineMemOperand::MOLoad, MemSize, MemSize);
12267     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12268     Chain = Value.getValue(1);
12269     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12270     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12271   }
12272
12273   MachineMemOperand *MMO =
12274     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12275                             MachineMemOperand::MOStore, MemSize, MemSize);
12276
12277   if (Opc != X86ISD::WIN_FTOL) {
12278     // Build the FP_TO_INT*_IN_MEM
12279     SDValue Ops[] = { Chain, Value, StackSlot };
12280     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12281                                            Ops, DstTy, MMO);
12282     return std::make_pair(FIST, StackSlot);
12283   } else {
12284     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12285       DAG.getVTList(MVT::Other, MVT::Glue),
12286       Chain, Value);
12287     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12288       MVT::i32, ftol.getValue(1));
12289     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12290       MVT::i32, eax.getValue(2));
12291     SDValue Ops[] = { eax, edx };
12292     SDValue pair = IsReplace
12293       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12294       : DAG.getMergeValues(Ops, DL);
12295     return std::make_pair(pair, SDValue());
12296   }
12297 }
12298
12299 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12300                               const X86Subtarget *Subtarget) {
12301   MVT VT = Op->getSimpleValueType(0);
12302   SDValue In = Op->getOperand(0);
12303   MVT InVT = In.getSimpleValueType();
12304   SDLoc dl(Op);
12305
12306   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12307     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12308
12309   // Optimize vectors in AVX mode:
12310   //
12311   //   v8i16 -> v8i32
12312   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12313   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12314   //   Concat upper and lower parts.
12315   //
12316   //   v4i32 -> v4i64
12317   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12318   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12319   //   Concat upper and lower parts.
12320   //
12321
12322   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12323       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12324       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12325     return SDValue();
12326
12327   if (Subtarget->hasInt256())
12328     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12329
12330   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12331   SDValue Undef = DAG.getUNDEF(InVT);
12332   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12333   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12334   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12335
12336   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12337                              VT.getVectorNumElements()/2);
12338
12339   OpLo = DAG.getBitcast(HVT, OpLo);
12340   OpHi = DAG.getBitcast(HVT, OpHi);
12341
12342   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12343 }
12344
12345 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12346                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12347   MVT VT = Op->getSimpleValueType(0);
12348   SDValue In = Op->getOperand(0);
12349   MVT InVT = In.getSimpleValueType();
12350   SDLoc DL(Op);
12351   unsigned int NumElts = VT.getVectorNumElements();
12352   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12353     return SDValue();
12354
12355   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12356     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12357
12358   assert(InVT.getVectorElementType() == MVT::i1);
12359   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12360   SDValue One =
12361    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12362   SDValue Zero =
12363    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12364
12365   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12366   if (VT.is512BitVector())
12367     return V;
12368   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12369 }
12370
12371 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12372                                SelectionDAG &DAG) {
12373   if (Subtarget->hasFp256())
12374     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12375       return Res;
12376
12377   return SDValue();
12378 }
12379
12380 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12381                                 SelectionDAG &DAG) {
12382   SDLoc DL(Op);
12383   MVT VT = Op.getSimpleValueType();
12384   SDValue In = Op.getOperand(0);
12385   MVT SVT = In.getSimpleValueType();
12386
12387   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12388     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12389
12390   if (Subtarget->hasFp256())
12391     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12392       return Res;
12393
12394   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12395          VT.getVectorNumElements() != SVT.getVectorNumElements());
12396   return SDValue();
12397 }
12398
12399 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12400   SDLoc DL(Op);
12401   MVT VT = Op.getSimpleValueType();
12402   SDValue In = Op.getOperand(0);
12403   MVT InVT = In.getSimpleValueType();
12404
12405   if (VT == MVT::i1) {
12406     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12407            "Invalid scalar TRUNCATE operation");
12408     if (InVT.getSizeInBits() >= 32)
12409       return SDValue();
12410     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12411     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12412   }
12413   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12414          "Invalid TRUNCATE operation");
12415
12416   // move vector to mask - truncate solution for SKX
12417   if (VT.getVectorElementType() == MVT::i1) {
12418     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12419         Subtarget->hasBWI())
12420       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12421     if ((InVT.is256BitVector() || InVT.is128BitVector())
12422         && InVT.getScalarSizeInBits() <= 16 &&
12423         Subtarget->hasBWI() && Subtarget->hasVLX())
12424       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12425     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12426         Subtarget->hasDQI())
12427       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12428     if ((InVT.is256BitVector() || InVT.is128BitVector())
12429         && InVT.getScalarSizeInBits() >= 32 &&
12430         Subtarget->hasDQI() && Subtarget->hasVLX())
12431       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12432   }
12433   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12434     if (VT.getVectorElementType().getSizeInBits() >=8)
12435       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12436
12437     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12438     unsigned NumElts = InVT.getVectorNumElements();
12439     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12440     if (InVT.getSizeInBits() < 512) {
12441       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12442       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12443       InVT = ExtVT;
12444     }
12445
12446     SDValue OneV =
12447      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12448     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12449     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12450   }
12451
12452   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12453     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12454     if (Subtarget->hasInt256()) {
12455       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12456       In = DAG.getBitcast(MVT::v8i32, In);
12457       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12458                                 ShufMask);
12459       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12460                          DAG.getIntPtrConstant(0, DL));
12461     }
12462
12463     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12464                                DAG.getIntPtrConstant(0, DL));
12465     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12466                                DAG.getIntPtrConstant(2, DL));
12467     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12468     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12469     static const int ShufMask[] = {0, 2, 4, 6};
12470     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12471   }
12472
12473   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12474     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12475     if (Subtarget->hasInt256()) {
12476       In = DAG.getBitcast(MVT::v32i8, In);
12477
12478       SmallVector<SDValue,32> pshufbMask;
12479       for (unsigned i = 0; i < 2; ++i) {
12480         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12481         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12482         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12483         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12484         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12485         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12486         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12487         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12488         for (unsigned j = 0; j < 8; ++j)
12489           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12490       }
12491       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12492       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12493       In = DAG.getBitcast(MVT::v4i64, In);
12494
12495       static const int ShufMask[] = {0,  2,  -1,  -1};
12496       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12497                                 &ShufMask[0]);
12498       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12499                        DAG.getIntPtrConstant(0, DL));
12500       return DAG.getBitcast(VT, In);
12501     }
12502
12503     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12504                                DAG.getIntPtrConstant(0, DL));
12505
12506     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12507                                DAG.getIntPtrConstant(4, DL));
12508
12509     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12510     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12511
12512     // The PSHUFB mask:
12513     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12514                                    -1, -1, -1, -1, -1, -1, -1, -1};
12515
12516     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12517     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12518     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12519
12520     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12521     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12522
12523     // The MOVLHPS Mask:
12524     static const int ShufMask2[] = {0, 1, 4, 5};
12525     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12526     return DAG.getBitcast(MVT::v8i16, res);
12527   }
12528
12529   // Handle truncation of V256 to V128 using shuffles.
12530   if (!VT.is128BitVector() || !InVT.is256BitVector())
12531     return SDValue();
12532
12533   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12534
12535   unsigned NumElems = VT.getVectorNumElements();
12536   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12537
12538   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12539   // Prepare truncation shuffle mask
12540   for (unsigned i = 0; i != NumElems; ++i)
12541     MaskVec[i] = i * 2;
12542   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12543                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12544   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12545                      DAG.getIntPtrConstant(0, DL));
12546 }
12547
12548 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12549                                            SelectionDAG &DAG) const {
12550   assert(!Op.getSimpleValueType().isVector());
12551
12552   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12553     /*IsSigned=*/ true, /*IsReplace=*/ false);
12554   SDValue FIST = Vals.first, StackSlot = Vals.second;
12555   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12556   if (!FIST.getNode()) return Op;
12557
12558   if (StackSlot.getNode())
12559     // Load the result.
12560     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12561                        FIST, StackSlot, MachinePointerInfo(),
12562                        false, false, false, 0);
12563
12564   // The node is the result.
12565   return FIST;
12566 }
12567
12568 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12569                                            SelectionDAG &DAG) const {
12570   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12571     /*IsSigned=*/ false, /*IsReplace=*/ false);
12572   SDValue FIST = Vals.first, StackSlot = Vals.second;
12573   assert(FIST.getNode() && "Unexpected failure");
12574
12575   if (StackSlot.getNode())
12576     // Load the result.
12577     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12578                        FIST, StackSlot, MachinePointerInfo(),
12579                        false, false, false, 0);
12580
12581   // The node is the result.
12582   return FIST;
12583 }
12584
12585 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12586   SDLoc DL(Op);
12587   MVT VT = Op.getSimpleValueType();
12588   SDValue In = Op.getOperand(0);
12589   MVT SVT = In.getSimpleValueType();
12590
12591   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12592
12593   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12594                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12595                                  In, DAG.getUNDEF(SVT)));
12596 }
12597
12598 /// The only differences between FABS and FNEG are the mask and the logic op.
12599 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12600 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12601   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12602          "Wrong opcode for lowering FABS or FNEG.");
12603
12604   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12605
12606   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12607   // into an FNABS. We'll lower the FABS after that if it is still in use.
12608   if (IsFABS)
12609     for (SDNode *User : Op->uses())
12610       if (User->getOpcode() == ISD::FNEG)
12611         return Op;
12612
12613   SDValue Op0 = Op.getOperand(0);
12614   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12615
12616   SDLoc dl(Op);
12617   MVT VT = Op.getSimpleValueType();
12618   // Assume scalar op for initialization; update for vector if needed.
12619   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12620   // generate a 16-byte vector constant and logic op even for the scalar case.
12621   // Using a 16-byte mask allows folding the load of the mask with
12622   // the logic op, so it can save (~4 bytes) on code size.
12623   MVT EltVT = VT;
12624   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12625   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12626   // decide if we should generate a 16-byte constant mask when we only need 4 or
12627   // 8 bytes for the scalar case.
12628   if (VT.isVector()) {
12629     EltVT = VT.getVectorElementType();
12630     NumElts = VT.getVectorNumElements();
12631   }
12632
12633   unsigned EltBits = EltVT.getSizeInBits();
12634   LLVMContext *Context = DAG.getContext();
12635   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12636   APInt MaskElt =
12637     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12638   Constant *C = ConstantInt::get(*Context, MaskElt);
12639   C = ConstantVector::getSplat(NumElts, C);
12640   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12641   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12642   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12643   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12644                              MachinePointerInfo::getConstantPool(),
12645                              false, false, false, Alignment);
12646
12647   if (VT.isVector()) {
12648     // For a vector, cast operands to a vector type, perform the logic op,
12649     // and cast the result back to the original value type.
12650     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12651     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12652     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12653                               : DAG.getBitcast(VecVT, Op0);
12654     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12655     return DAG.getBitcast(VT,
12656                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12657   }
12658
12659   // If not vector, then scalar.
12660   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12661   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12662   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12663 }
12664
12665 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12666   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12667   LLVMContext *Context = DAG.getContext();
12668   SDValue Op0 = Op.getOperand(0);
12669   SDValue Op1 = Op.getOperand(1);
12670   SDLoc dl(Op);
12671   MVT VT = Op.getSimpleValueType();
12672   MVT SrcVT = Op1.getSimpleValueType();
12673
12674   // If second operand is smaller, extend it first.
12675   if (SrcVT.bitsLT(VT)) {
12676     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12677     SrcVT = VT;
12678   }
12679   // And if it is bigger, shrink it first.
12680   if (SrcVT.bitsGT(VT)) {
12681     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12682     SrcVT = VT;
12683   }
12684
12685   // At this point the operands and the result should have the same
12686   // type, and that won't be f80 since that is not custom lowered.
12687
12688   const fltSemantics &Sem =
12689       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12690   const unsigned SizeInBits = VT.getSizeInBits();
12691
12692   SmallVector<Constant *, 4> CV(
12693       VT == MVT::f64 ? 2 : 4,
12694       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12695
12696   // First, clear all bits but the sign bit from the second operand (sign).
12697   CV[0] = ConstantFP::get(*Context,
12698                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12699   Constant *C = ConstantVector::get(CV);
12700   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12701   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12702                               MachinePointerInfo::getConstantPool(),
12703                               false, false, false, 16);
12704   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12705
12706   // Next, clear the sign bit from the first operand (magnitude).
12707   // If it's a constant, we can clear it here.
12708   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12709     APFloat APF = Op0CN->getValueAPF();
12710     // If the magnitude is a positive zero, the sign bit alone is enough.
12711     if (APF.isPosZero())
12712       return SignBit;
12713     APF.clearSign();
12714     CV[0] = ConstantFP::get(*Context, APF);
12715   } else {
12716     CV[0] = ConstantFP::get(
12717         *Context,
12718         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12719   }
12720   C = ConstantVector::get(CV);
12721   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12722   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12723                             MachinePointerInfo::getConstantPool(),
12724                             false, false, false, 16);
12725   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12726   if (!isa<ConstantFPSDNode>(Op0))
12727     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12728
12729   // OR the magnitude value with the sign bit.
12730   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12731 }
12732
12733 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12734   SDValue N0 = Op.getOperand(0);
12735   SDLoc dl(Op);
12736   MVT VT = Op.getSimpleValueType();
12737
12738   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12739   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12740                                   DAG.getConstant(1, dl, VT));
12741   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12742 }
12743
12744 // Check whether an OR'd tree is PTEST-able.
12745 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12746                                       SelectionDAG &DAG) {
12747   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12748
12749   if (!Subtarget->hasSSE41())
12750     return SDValue();
12751
12752   if (!Op->hasOneUse())
12753     return SDValue();
12754
12755   SDNode *N = Op.getNode();
12756   SDLoc DL(N);
12757
12758   SmallVector<SDValue, 8> Opnds;
12759   DenseMap<SDValue, unsigned> VecInMap;
12760   SmallVector<SDValue, 8> VecIns;
12761   EVT VT = MVT::Other;
12762
12763   // Recognize a special case where a vector is casted into wide integer to
12764   // test all 0s.
12765   Opnds.push_back(N->getOperand(0));
12766   Opnds.push_back(N->getOperand(1));
12767
12768   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12769     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12770     // BFS traverse all OR'd operands.
12771     if (I->getOpcode() == ISD::OR) {
12772       Opnds.push_back(I->getOperand(0));
12773       Opnds.push_back(I->getOperand(1));
12774       // Re-evaluate the number of nodes to be traversed.
12775       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12776       continue;
12777     }
12778
12779     // Quit if a non-EXTRACT_VECTOR_ELT
12780     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12781       return SDValue();
12782
12783     // Quit if without a constant index.
12784     SDValue Idx = I->getOperand(1);
12785     if (!isa<ConstantSDNode>(Idx))
12786       return SDValue();
12787
12788     SDValue ExtractedFromVec = I->getOperand(0);
12789     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12790     if (M == VecInMap.end()) {
12791       VT = ExtractedFromVec.getValueType();
12792       // Quit if not 128/256-bit vector.
12793       if (!VT.is128BitVector() && !VT.is256BitVector())
12794         return SDValue();
12795       // Quit if not the same type.
12796       if (VecInMap.begin() != VecInMap.end() &&
12797           VT != VecInMap.begin()->first.getValueType())
12798         return SDValue();
12799       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12800       VecIns.push_back(ExtractedFromVec);
12801     }
12802     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12803   }
12804
12805   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12806          "Not extracted from 128-/256-bit vector.");
12807
12808   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12809
12810   for (DenseMap<SDValue, unsigned>::const_iterator
12811         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12812     // Quit if not all elements are used.
12813     if (I->second != FullMask)
12814       return SDValue();
12815   }
12816
12817   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12818
12819   // Cast all vectors into TestVT for PTEST.
12820   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12821     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12822
12823   // If more than one full vectors are evaluated, OR them first before PTEST.
12824   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12825     // Each iteration will OR 2 nodes and append the result until there is only
12826     // 1 node left, i.e. the final OR'd value of all vectors.
12827     SDValue LHS = VecIns[Slot];
12828     SDValue RHS = VecIns[Slot + 1];
12829     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12830   }
12831
12832   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12833                      VecIns.back(), VecIns.back());
12834 }
12835
12836 /// \brief return true if \c Op has a use that doesn't just read flags.
12837 static bool hasNonFlagsUse(SDValue Op) {
12838   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12839        ++UI) {
12840     SDNode *User = *UI;
12841     unsigned UOpNo = UI.getOperandNo();
12842     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12843       // Look pass truncate.
12844       UOpNo = User->use_begin().getOperandNo();
12845       User = *User->use_begin();
12846     }
12847
12848     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12849         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12850       return true;
12851   }
12852   return false;
12853 }
12854
12855 /// Emit nodes that will be selected as "test Op0,Op0", or something
12856 /// equivalent.
12857 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12858                                     SelectionDAG &DAG) const {
12859   if (Op.getValueType() == MVT::i1) {
12860     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12861     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12862                        DAG.getConstant(0, dl, MVT::i8));
12863   }
12864   // CF and OF aren't always set the way we want. Determine which
12865   // of these we need.
12866   bool NeedCF = false;
12867   bool NeedOF = false;
12868   switch (X86CC) {
12869   default: break;
12870   case X86::COND_A: case X86::COND_AE:
12871   case X86::COND_B: case X86::COND_BE:
12872     NeedCF = true;
12873     break;
12874   case X86::COND_G: case X86::COND_GE:
12875   case X86::COND_L: case X86::COND_LE:
12876   case X86::COND_O: case X86::COND_NO: {
12877     // Check if we really need to set the
12878     // Overflow flag. If NoSignedWrap is present
12879     // that is not actually needed.
12880     switch (Op->getOpcode()) {
12881     case ISD::ADD:
12882     case ISD::SUB:
12883     case ISD::MUL:
12884     case ISD::SHL: {
12885       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12886       if (BinNode->Flags.hasNoSignedWrap())
12887         break;
12888     }
12889     default:
12890       NeedOF = true;
12891       break;
12892     }
12893     break;
12894   }
12895   }
12896   // See if we can use the EFLAGS value from the operand instead of
12897   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12898   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12899   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12900     // Emit a CMP with 0, which is the TEST pattern.
12901     //if (Op.getValueType() == MVT::i1)
12902     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12903     //                     DAG.getConstant(0, MVT::i1));
12904     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12905                        DAG.getConstant(0, dl, Op.getValueType()));
12906   }
12907   unsigned Opcode = 0;
12908   unsigned NumOperands = 0;
12909
12910   // Truncate operations may prevent the merge of the SETCC instruction
12911   // and the arithmetic instruction before it. Attempt to truncate the operands
12912   // of the arithmetic instruction and use a reduced bit-width instruction.
12913   bool NeedTruncation = false;
12914   SDValue ArithOp = Op;
12915   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12916     SDValue Arith = Op->getOperand(0);
12917     // Both the trunc and the arithmetic op need to have one user each.
12918     if (Arith->hasOneUse())
12919       switch (Arith.getOpcode()) {
12920         default: break;
12921         case ISD::ADD:
12922         case ISD::SUB:
12923         case ISD::AND:
12924         case ISD::OR:
12925         case ISD::XOR: {
12926           NeedTruncation = true;
12927           ArithOp = Arith;
12928         }
12929       }
12930   }
12931
12932   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12933   // which may be the result of a CAST.  We use the variable 'Op', which is the
12934   // non-casted variable when we check for possible users.
12935   switch (ArithOp.getOpcode()) {
12936   case ISD::ADD:
12937     // Due to an isel shortcoming, be conservative if this add is likely to be
12938     // selected as part of a load-modify-store instruction. When the root node
12939     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12940     // uses of other nodes in the match, such as the ADD in this case. This
12941     // leads to the ADD being left around and reselected, with the result being
12942     // two adds in the output.  Alas, even if none our users are stores, that
12943     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12944     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12945     // climbing the DAG back to the root, and it doesn't seem to be worth the
12946     // effort.
12947     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12948          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12949       if (UI->getOpcode() != ISD::CopyToReg &&
12950           UI->getOpcode() != ISD::SETCC &&
12951           UI->getOpcode() != ISD::STORE)
12952         goto default_case;
12953
12954     if (ConstantSDNode *C =
12955         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12956       // An add of one will be selected as an INC.
12957       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12958         Opcode = X86ISD::INC;
12959         NumOperands = 1;
12960         break;
12961       }
12962
12963       // An add of negative one (subtract of one) will be selected as a DEC.
12964       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12965         Opcode = X86ISD::DEC;
12966         NumOperands = 1;
12967         break;
12968       }
12969     }
12970
12971     // Otherwise use a regular EFLAGS-setting add.
12972     Opcode = X86ISD::ADD;
12973     NumOperands = 2;
12974     break;
12975   case ISD::SHL:
12976   case ISD::SRL:
12977     // If we have a constant logical shift that's only used in a comparison
12978     // against zero turn it into an equivalent AND. This allows turning it into
12979     // a TEST instruction later.
12980     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12981         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12982       EVT VT = Op.getValueType();
12983       unsigned BitWidth = VT.getSizeInBits();
12984       unsigned ShAmt = Op->getConstantOperandVal(1);
12985       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12986         break;
12987       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12988                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12989                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12990       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12991         break;
12992       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12993                                 DAG.getConstant(Mask, dl, VT));
12994       DAG.ReplaceAllUsesWith(Op, New);
12995       Op = New;
12996     }
12997     break;
12998
12999   case ISD::AND:
13000     // If the primary and result isn't used, don't bother using X86ISD::AND,
13001     // because a TEST instruction will be better.
13002     if (!hasNonFlagsUse(Op))
13003       break;
13004     // FALL THROUGH
13005   case ISD::SUB:
13006   case ISD::OR:
13007   case ISD::XOR:
13008     // Due to the ISEL shortcoming noted above, be conservative if this op is
13009     // likely to be selected as part of a load-modify-store instruction.
13010     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13011            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13012       if (UI->getOpcode() == ISD::STORE)
13013         goto default_case;
13014
13015     // Otherwise use a regular EFLAGS-setting instruction.
13016     switch (ArithOp.getOpcode()) {
13017     default: llvm_unreachable("unexpected operator!");
13018     case ISD::SUB: Opcode = X86ISD::SUB; break;
13019     case ISD::XOR: Opcode = X86ISD::XOR; break;
13020     case ISD::AND: Opcode = X86ISD::AND; break;
13021     case ISD::OR: {
13022       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13023         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13024         if (EFLAGS.getNode())
13025           return EFLAGS;
13026       }
13027       Opcode = X86ISD::OR;
13028       break;
13029     }
13030     }
13031
13032     NumOperands = 2;
13033     break;
13034   case X86ISD::ADD:
13035   case X86ISD::SUB:
13036   case X86ISD::INC:
13037   case X86ISD::DEC:
13038   case X86ISD::OR:
13039   case X86ISD::XOR:
13040   case X86ISD::AND:
13041     return SDValue(Op.getNode(), 1);
13042   default:
13043   default_case:
13044     break;
13045   }
13046
13047   // If we found that truncation is beneficial, perform the truncation and
13048   // update 'Op'.
13049   if (NeedTruncation) {
13050     EVT VT = Op.getValueType();
13051     SDValue WideVal = Op->getOperand(0);
13052     EVT WideVT = WideVal.getValueType();
13053     unsigned ConvertedOp = 0;
13054     // Use a target machine opcode to prevent further DAGCombine
13055     // optimizations that may separate the arithmetic operations
13056     // from the setcc node.
13057     switch (WideVal.getOpcode()) {
13058       default: break;
13059       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13060       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13061       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13062       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13063       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13064     }
13065
13066     if (ConvertedOp) {
13067       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13068       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13069         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13070         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13071         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13072       }
13073     }
13074   }
13075
13076   if (Opcode == 0)
13077     // Emit a CMP with 0, which is the TEST pattern.
13078     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13079                        DAG.getConstant(0, dl, Op.getValueType()));
13080
13081   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13082   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13083
13084   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13085   DAG.ReplaceAllUsesWith(Op, New);
13086   return SDValue(New.getNode(), 1);
13087 }
13088
13089 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13090 /// equivalent.
13091 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13092                                    SDLoc dl, SelectionDAG &DAG) const {
13093   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13094     if (C->getAPIntValue() == 0)
13095       return EmitTest(Op0, X86CC, dl, DAG);
13096
13097      if (Op0.getValueType() == MVT::i1)
13098        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13099   }
13100
13101   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13102        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13103     // Do the comparison at i32 if it's smaller, besides the Atom case.
13104     // This avoids subregister aliasing issues. Keep the smaller reference
13105     // if we're optimizing for size, however, as that'll allow better folding
13106     // of memory operations.
13107     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13108         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13109             Attribute::MinSize) &&
13110         !Subtarget->isAtom()) {
13111       unsigned ExtendOp =
13112           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13113       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13114       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13115     }
13116     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13117     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13118     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13119                               Op0, Op1);
13120     return SDValue(Sub.getNode(), 1);
13121   }
13122   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13123 }
13124
13125 /// Convert a comparison if required by the subtarget.
13126 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13127                                                  SelectionDAG &DAG) const {
13128   // If the subtarget does not support the FUCOMI instruction, floating-point
13129   // comparisons have to be converted.
13130   if (Subtarget->hasCMov() ||
13131       Cmp.getOpcode() != X86ISD::CMP ||
13132       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13133       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13134     return Cmp;
13135
13136   // The instruction selector will select an FUCOM instruction instead of
13137   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13138   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13139   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13140   SDLoc dl(Cmp);
13141   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13142   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13143   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13144                             DAG.getConstant(8, dl, MVT::i8));
13145   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13146   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13147 }
13148
13149 /// The minimum architected relative accuracy is 2^-12. We need one
13150 /// Newton-Raphson step to have a good float result (24 bits of precision).
13151 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13152                                             DAGCombinerInfo &DCI,
13153                                             unsigned &RefinementSteps,
13154                                             bool &UseOneConstNR) const {
13155   EVT VT = Op.getValueType();
13156   const char *RecipOp;
13157
13158   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13159   // TODO: Add support for AVX512 (v16f32).
13160   // It is likely not profitable to do this for f64 because a double-precision
13161   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13162   // instructions: convert to single, rsqrtss, convert back to double, refine
13163   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13164   // along with FMA, this could be a throughput win.
13165   if (VT == MVT::f32 && Subtarget->hasSSE1())
13166     RecipOp = "sqrtf";
13167   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13168            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13169     RecipOp = "vec-sqrtf";
13170   else
13171     return SDValue();
13172
13173   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13174   if (!Recips.isEnabled(RecipOp))
13175     return SDValue();
13176
13177   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13178   UseOneConstNR = false;
13179   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13180 }
13181
13182 /// The minimum architected relative accuracy is 2^-12. We need one
13183 /// Newton-Raphson step to have a good float result (24 bits of precision).
13184 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13185                                             DAGCombinerInfo &DCI,
13186                                             unsigned &RefinementSteps) const {
13187   EVT VT = Op.getValueType();
13188   const char *RecipOp;
13189
13190   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13191   // TODO: Add support for AVX512 (v16f32).
13192   // It is likely not profitable to do this for f64 because a double-precision
13193   // reciprocal estimate with refinement on x86 prior to FMA requires
13194   // 15 instructions: convert to single, rcpss, convert back to double, refine
13195   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13196   // along with FMA, this could be a throughput win.
13197   if (VT == MVT::f32 && Subtarget->hasSSE1())
13198     RecipOp = "divf";
13199   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13200            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13201     RecipOp = "vec-divf";
13202   else
13203     return SDValue();
13204
13205   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13206   if (!Recips.isEnabled(RecipOp))
13207     return SDValue();
13208
13209   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13210   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13211 }
13212
13213 /// If we have at least two divisions that use the same divisor, convert to
13214 /// multplication by a reciprocal. This may need to be adjusted for a given
13215 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13216 /// This is because we still need one division to calculate the reciprocal and
13217 /// then we need two multiplies by that reciprocal as replacements for the
13218 /// original divisions.
13219 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13220   return NumUsers > 1;
13221 }
13222
13223 static bool isAllOnes(SDValue V) {
13224   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13225   return C && C->isAllOnesValue();
13226 }
13227
13228 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13229 /// if it's possible.
13230 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13231                                      SDLoc dl, SelectionDAG &DAG) const {
13232   SDValue Op0 = And.getOperand(0);
13233   SDValue Op1 = And.getOperand(1);
13234   if (Op0.getOpcode() == ISD::TRUNCATE)
13235     Op0 = Op0.getOperand(0);
13236   if (Op1.getOpcode() == ISD::TRUNCATE)
13237     Op1 = Op1.getOperand(0);
13238
13239   SDValue LHS, RHS;
13240   if (Op1.getOpcode() == ISD::SHL)
13241     std::swap(Op0, Op1);
13242   if (Op0.getOpcode() == ISD::SHL) {
13243     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13244       if (And00C->getZExtValue() == 1) {
13245         // If we looked past a truncate, check that it's only truncating away
13246         // known zeros.
13247         unsigned BitWidth = Op0.getValueSizeInBits();
13248         unsigned AndBitWidth = And.getValueSizeInBits();
13249         if (BitWidth > AndBitWidth) {
13250           APInt Zeros, Ones;
13251           DAG.computeKnownBits(Op0, Zeros, Ones);
13252           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13253             return SDValue();
13254         }
13255         LHS = Op1;
13256         RHS = Op0.getOperand(1);
13257       }
13258   } else if (Op1.getOpcode() == ISD::Constant) {
13259     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13260     uint64_t AndRHSVal = AndRHS->getZExtValue();
13261     SDValue AndLHS = Op0;
13262
13263     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13264       LHS = AndLHS.getOperand(0);
13265       RHS = AndLHS.getOperand(1);
13266     }
13267
13268     // Use BT if the immediate can't be encoded in a TEST instruction.
13269     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13270       LHS = AndLHS;
13271       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13272     }
13273   }
13274
13275   if (LHS.getNode()) {
13276     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13277     // instruction.  Since the shift amount is in-range-or-undefined, we know
13278     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13279     // the encoding for the i16 version is larger than the i32 version.
13280     // Also promote i16 to i32 for performance / code size reason.
13281     if (LHS.getValueType() == MVT::i8 ||
13282         LHS.getValueType() == MVT::i16)
13283       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13284
13285     // If the operand types disagree, extend the shift amount to match.  Since
13286     // BT ignores high bits (like shifts) we can use anyextend.
13287     if (LHS.getValueType() != RHS.getValueType())
13288       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13289
13290     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13291     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13292     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13293                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13294   }
13295
13296   return SDValue();
13297 }
13298
13299 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13300 /// mask CMPs.
13301 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13302                               SDValue &Op1) {
13303   unsigned SSECC;
13304   bool Swap = false;
13305
13306   // SSE Condition code mapping:
13307   //  0 - EQ
13308   //  1 - LT
13309   //  2 - LE
13310   //  3 - UNORD
13311   //  4 - NEQ
13312   //  5 - NLT
13313   //  6 - NLE
13314   //  7 - ORD
13315   switch (SetCCOpcode) {
13316   default: llvm_unreachable("Unexpected SETCC condition");
13317   case ISD::SETOEQ:
13318   case ISD::SETEQ:  SSECC = 0; break;
13319   case ISD::SETOGT:
13320   case ISD::SETGT:  Swap = true; // Fallthrough
13321   case ISD::SETLT:
13322   case ISD::SETOLT: SSECC = 1; break;
13323   case ISD::SETOGE:
13324   case ISD::SETGE:  Swap = true; // Fallthrough
13325   case ISD::SETLE:
13326   case ISD::SETOLE: SSECC = 2; break;
13327   case ISD::SETUO:  SSECC = 3; break;
13328   case ISD::SETUNE:
13329   case ISD::SETNE:  SSECC = 4; break;
13330   case ISD::SETULE: Swap = true; // Fallthrough
13331   case ISD::SETUGE: SSECC = 5; break;
13332   case ISD::SETULT: Swap = true; // Fallthrough
13333   case ISD::SETUGT: SSECC = 6; break;
13334   case ISD::SETO:   SSECC = 7; break;
13335   case ISD::SETUEQ:
13336   case ISD::SETONE: SSECC = 8; break;
13337   }
13338   if (Swap)
13339     std::swap(Op0, Op1);
13340
13341   return SSECC;
13342 }
13343
13344 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13345 // ones, and then concatenate the result back.
13346 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13347   MVT VT = Op.getSimpleValueType();
13348
13349   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13350          "Unsupported value type for operation");
13351
13352   unsigned NumElems = VT.getVectorNumElements();
13353   SDLoc dl(Op);
13354   SDValue CC = Op.getOperand(2);
13355
13356   // Extract the LHS vectors
13357   SDValue LHS = Op.getOperand(0);
13358   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13359   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13360
13361   // Extract the RHS vectors
13362   SDValue RHS = Op.getOperand(1);
13363   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13364   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13365
13366   // Issue the operation on the smaller types and concatenate the result back
13367   MVT EltVT = VT.getVectorElementType();
13368   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13369   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13370                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13371                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13372 }
13373
13374 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13375   SDValue Op0 = Op.getOperand(0);
13376   SDValue Op1 = Op.getOperand(1);
13377   SDValue CC = Op.getOperand(2);
13378   MVT VT = Op.getSimpleValueType();
13379   SDLoc dl(Op);
13380
13381   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13382          "Unexpected type for boolean compare operation");
13383   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13384   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13385                                DAG.getConstant(-1, dl, VT));
13386   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13387                                DAG.getConstant(-1, dl, VT));
13388   switch (SetCCOpcode) {
13389   default: llvm_unreachable("Unexpected SETCC condition");
13390   case ISD::SETEQ:
13391     // (x == y) -> ~(x ^ y)
13392     return DAG.getNode(ISD::XOR, dl, VT,
13393                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13394                        DAG.getConstant(-1, dl, VT));
13395   case ISD::SETNE:
13396     // (x != y) -> (x ^ y)
13397     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13398   case ISD::SETUGT:
13399   case ISD::SETGT:
13400     // (x > y) -> (x & ~y)
13401     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13402   case ISD::SETULT:
13403   case ISD::SETLT:
13404     // (x < y) -> (~x & y)
13405     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13406   case ISD::SETULE:
13407   case ISD::SETLE:
13408     // (x <= y) -> (~x | y)
13409     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13410   case ISD::SETUGE:
13411   case ISD::SETGE:
13412     // (x >=y) -> (x | ~y)
13413     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13414   }
13415 }
13416
13417 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13418                                      const X86Subtarget *Subtarget) {
13419   SDValue Op0 = Op.getOperand(0);
13420   SDValue Op1 = Op.getOperand(1);
13421   SDValue CC = Op.getOperand(2);
13422   MVT VT = Op.getSimpleValueType();
13423   SDLoc dl(Op);
13424
13425   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13426          Op.getValueType().getScalarType() == MVT::i1 &&
13427          "Cannot set masked compare for this operation");
13428
13429   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13430   unsigned  Opc = 0;
13431   bool Unsigned = false;
13432   bool Swap = false;
13433   unsigned SSECC;
13434   switch (SetCCOpcode) {
13435   default: llvm_unreachable("Unexpected SETCC condition");
13436   case ISD::SETNE:  SSECC = 4; break;
13437   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13438   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13439   case ISD::SETLT:  Swap = true; //fall-through
13440   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13441   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13442   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13443   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13444   case ISD::SETULE: Unsigned = true; //fall-through
13445   case ISD::SETLE:  SSECC = 2; break;
13446   }
13447
13448   if (Swap)
13449     std::swap(Op0, Op1);
13450   if (Opc)
13451     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13452   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13453   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13454                      DAG.getConstant(SSECC, dl, MVT::i8));
13455 }
13456
13457 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13458 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13459 /// return an empty value.
13460 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13461 {
13462   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13463   if (!BV)
13464     return SDValue();
13465
13466   MVT VT = Op1.getSimpleValueType();
13467   MVT EVT = VT.getVectorElementType();
13468   unsigned n = VT.getVectorNumElements();
13469   SmallVector<SDValue, 8> ULTOp1;
13470
13471   for (unsigned i = 0; i < n; ++i) {
13472     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13473     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13474       return SDValue();
13475
13476     // Avoid underflow.
13477     APInt Val = Elt->getAPIntValue();
13478     if (Val == 0)
13479       return SDValue();
13480
13481     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13482   }
13483
13484   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13485 }
13486
13487 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13488                            SelectionDAG &DAG) {
13489   SDValue Op0 = Op.getOperand(0);
13490   SDValue Op1 = Op.getOperand(1);
13491   SDValue CC = Op.getOperand(2);
13492   MVT VT = Op.getSimpleValueType();
13493   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13494   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13495   SDLoc dl(Op);
13496
13497   if (isFP) {
13498 #ifndef NDEBUG
13499     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13500     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13501 #endif
13502
13503     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13504     unsigned Opc = X86ISD::CMPP;
13505     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13506       assert(VT.getVectorNumElements() <= 16);
13507       Opc = X86ISD::CMPM;
13508     }
13509     // In the two special cases we can't handle, emit two comparisons.
13510     if (SSECC == 8) {
13511       unsigned CC0, CC1;
13512       unsigned CombineOpc;
13513       if (SetCCOpcode == ISD::SETUEQ) {
13514         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13515       } else {
13516         assert(SetCCOpcode == ISD::SETONE);
13517         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13518       }
13519
13520       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13521                                  DAG.getConstant(CC0, dl, MVT::i8));
13522       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13523                                  DAG.getConstant(CC1, dl, MVT::i8));
13524       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13525     }
13526     // Handle all other FP comparisons here.
13527     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13528                        DAG.getConstant(SSECC, dl, MVT::i8));
13529   }
13530
13531   // Break 256-bit integer vector compare into smaller ones.
13532   if (VT.is256BitVector() && !Subtarget->hasInt256())
13533     return Lower256IntVSETCC(Op, DAG);
13534
13535   EVT OpVT = Op1.getValueType();
13536   if (OpVT.getVectorElementType() == MVT::i1)
13537     return LowerBoolVSETCC_AVX512(Op, DAG);
13538
13539   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13540   if (Subtarget->hasAVX512()) {
13541     if (Op1.getValueType().is512BitVector() ||
13542         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13543         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13544       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13545
13546     // In AVX-512 architecture setcc returns mask with i1 elements,
13547     // But there is no compare instruction for i8 and i16 elements in KNL.
13548     // We are not talking about 512-bit operands in this case, these
13549     // types are illegal.
13550     if (MaskResult &&
13551         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13552          OpVT.getVectorElementType().getSizeInBits() >= 8))
13553       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13554                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13555   }
13556
13557   // We are handling one of the integer comparisons here.  Since SSE only has
13558   // GT and EQ comparisons for integer, swapping operands and multiple
13559   // operations may be required for some comparisons.
13560   unsigned Opc;
13561   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13562   bool Subus = false;
13563
13564   switch (SetCCOpcode) {
13565   default: llvm_unreachable("Unexpected SETCC condition");
13566   case ISD::SETNE:  Invert = true;
13567   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13568   case ISD::SETLT:  Swap = true;
13569   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13570   case ISD::SETGE:  Swap = true;
13571   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13572                     Invert = true; break;
13573   case ISD::SETULT: Swap = true;
13574   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13575                     FlipSigns = true; break;
13576   case ISD::SETUGE: Swap = true;
13577   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13578                     FlipSigns = true; Invert = true; break;
13579   }
13580
13581   // Special case: Use min/max operations for SETULE/SETUGE
13582   MVT VET = VT.getVectorElementType();
13583   bool hasMinMax =
13584        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13585     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13586
13587   if (hasMinMax) {
13588     switch (SetCCOpcode) {
13589     default: break;
13590     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13591     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13592     }
13593
13594     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13595   }
13596
13597   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13598   if (!MinMax && hasSubus) {
13599     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13600     // Op0 u<= Op1:
13601     //   t = psubus Op0, Op1
13602     //   pcmpeq t, <0..0>
13603     switch (SetCCOpcode) {
13604     default: break;
13605     case ISD::SETULT: {
13606       // If the comparison is against a constant we can turn this into a
13607       // setule.  With psubus, setule does not require a swap.  This is
13608       // beneficial because the constant in the register is no longer
13609       // destructed as the destination so it can be hoisted out of a loop.
13610       // Only do this pre-AVX since vpcmp* is no longer destructive.
13611       if (Subtarget->hasAVX())
13612         break;
13613       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13614       if (ULEOp1.getNode()) {
13615         Op1 = ULEOp1;
13616         Subus = true; Invert = false; Swap = false;
13617       }
13618       break;
13619     }
13620     // Psubus is better than flip-sign because it requires no inversion.
13621     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13622     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13623     }
13624
13625     if (Subus) {
13626       Opc = X86ISD::SUBUS;
13627       FlipSigns = false;
13628     }
13629   }
13630
13631   if (Swap)
13632     std::swap(Op0, Op1);
13633
13634   // Check that the operation in question is available (most are plain SSE2,
13635   // but PCMPGTQ and PCMPEQQ have different requirements).
13636   if (VT == MVT::v2i64) {
13637     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13638       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13639
13640       // First cast everything to the right type.
13641       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13642       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13643
13644       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13645       // bits of the inputs before performing those operations. The lower
13646       // compare is always unsigned.
13647       SDValue SB;
13648       if (FlipSigns) {
13649         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13650       } else {
13651         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13652         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13653         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13654                          Sign, Zero, Sign, Zero);
13655       }
13656       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13657       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13658
13659       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13660       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13661       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13662
13663       // Create masks for only the low parts/high parts of the 64 bit integers.
13664       static const int MaskHi[] = { 1, 1, 3, 3 };
13665       static const int MaskLo[] = { 0, 0, 2, 2 };
13666       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13667       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13668       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13669
13670       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13671       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13672
13673       if (Invert)
13674         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13675
13676       return DAG.getBitcast(VT, Result);
13677     }
13678
13679     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13680       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13681       // pcmpeqd + pshufd + pand.
13682       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13683
13684       // First cast everything to the right type.
13685       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13686       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13687
13688       // Do the compare.
13689       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13690
13691       // Make sure the lower and upper halves are both all-ones.
13692       static const int Mask[] = { 1, 0, 3, 2 };
13693       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13694       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13695
13696       if (Invert)
13697         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13698
13699       return DAG.getBitcast(VT, Result);
13700     }
13701   }
13702
13703   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13704   // bits of the inputs before performing those operations.
13705   if (FlipSigns) {
13706     EVT EltVT = VT.getVectorElementType();
13707     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13708                                  VT);
13709     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13710     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13711   }
13712
13713   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13714
13715   // If the logical-not of the result is required, perform that now.
13716   if (Invert)
13717     Result = DAG.getNOT(dl, Result, VT);
13718
13719   if (MinMax)
13720     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13721
13722   if (Subus)
13723     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13724                          getZeroVector(VT, Subtarget, DAG, dl));
13725
13726   return Result;
13727 }
13728
13729 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13730
13731   MVT VT = Op.getSimpleValueType();
13732
13733   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13734
13735   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13736          && "SetCC type must be 8-bit or 1-bit integer");
13737   SDValue Op0 = Op.getOperand(0);
13738   SDValue Op1 = Op.getOperand(1);
13739   SDLoc dl(Op);
13740   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13741
13742   // Optimize to BT if possible.
13743   // Lower (X & (1 << N)) == 0 to BT(X, N).
13744   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13745   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13746   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13747       Op1.getOpcode() == ISD::Constant &&
13748       cast<ConstantSDNode>(Op1)->isNullValue() &&
13749       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13750     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13751     if (NewSetCC.getNode()) {
13752       if (VT == MVT::i1)
13753         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13754       return NewSetCC;
13755     }
13756   }
13757
13758   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13759   // these.
13760   if (Op1.getOpcode() == ISD::Constant &&
13761       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13762        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13763       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13764
13765     // If the input is a setcc, then reuse the input setcc or use a new one with
13766     // the inverted condition.
13767     if (Op0.getOpcode() == X86ISD::SETCC) {
13768       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13769       bool Invert = (CC == ISD::SETNE) ^
13770         cast<ConstantSDNode>(Op1)->isNullValue();
13771       if (!Invert)
13772         return Op0;
13773
13774       CCode = X86::GetOppositeBranchCondition(CCode);
13775       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13776                                   DAG.getConstant(CCode, dl, MVT::i8),
13777                                   Op0.getOperand(1));
13778       if (VT == MVT::i1)
13779         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13780       return SetCC;
13781     }
13782   }
13783   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13784       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13785       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13786
13787     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13788     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13789   }
13790
13791   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13792   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13793   if (X86CC == X86::COND_INVALID)
13794     return SDValue();
13795
13796   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13797   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13798   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13799                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13800   if (VT == MVT::i1)
13801     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13802   return SetCC;
13803 }
13804
13805 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13806 static bool isX86LogicalCmp(SDValue Op) {
13807   unsigned Opc = Op.getNode()->getOpcode();
13808   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13809       Opc == X86ISD::SAHF)
13810     return true;
13811   if (Op.getResNo() == 1 &&
13812       (Opc == X86ISD::ADD ||
13813        Opc == X86ISD::SUB ||
13814        Opc == X86ISD::ADC ||
13815        Opc == X86ISD::SBB ||
13816        Opc == X86ISD::SMUL ||
13817        Opc == X86ISD::UMUL ||
13818        Opc == X86ISD::INC ||
13819        Opc == X86ISD::DEC ||
13820        Opc == X86ISD::OR ||
13821        Opc == X86ISD::XOR ||
13822        Opc == X86ISD::AND))
13823     return true;
13824
13825   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13826     return true;
13827
13828   return false;
13829 }
13830
13831 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13832   if (V.getOpcode() != ISD::TRUNCATE)
13833     return false;
13834
13835   SDValue VOp0 = V.getOperand(0);
13836   unsigned InBits = VOp0.getValueSizeInBits();
13837   unsigned Bits = V.getValueSizeInBits();
13838   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13839 }
13840
13841 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13842   bool addTest = true;
13843   SDValue Cond  = Op.getOperand(0);
13844   SDValue Op1 = Op.getOperand(1);
13845   SDValue Op2 = Op.getOperand(2);
13846   SDLoc DL(Op);
13847   EVT VT = Op1.getValueType();
13848   SDValue CC;
13849
13850   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13851   // are available or VBLENDV if AVX is available.
13852   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13853   if (Cond.getOpcode() == ISD::SETCC &&
13854       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13855        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13856       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13857     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13858     int SSECC = translateX86FSETCC(
13859         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13860
13861     if (SSECC != 8) {
13862       if (Subtarget->hasAVX512()) {
13863         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13864                                   DAG.getConstant(SSECC, DL, MVT::i8));
13865         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13866       }
13867
13868       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13869                                 DAG.getConstant(SSECC, DL, MVT::i8));
13870
13871       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13872       // of 3 logic instructions for size savings and potentially speed.
13873       // Unfortunately, there is no scalar form of VBLENDV.
13874
13875       // If either operand is a constant, don't try this. We can expect to
13876       // optimize away at least one of the logic instructions later in that
13877       // case, so that sequence would be faster than a variable blend.
13878
13879       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13880       // uses XMM0 as the selection register. That may need just as many
13881       // instructions as the AND/ANDN/OR sequence due to register moves, so
13882       // don't bother.
13883
13884       if (Subtarget->hasAVX() &&
13885           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13886
13887         // Convert to vectors, do a VSELECT, and convert back to scalar.
13888         // All of the conversions should be optimized away.
13889
13890         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13891         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13892         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13893         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13894
13895         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13896         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13897
13898         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13899
13900         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13901                            VSel, DAG.getIntPtrConstant(0, DL));
13902       }
13903       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13904       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13905       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13906     }
13907   }
13908
13909     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13910       SDValue Op1Scalar;
13911       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13912         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13913       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13914         Op1Scalar = Op1.getOperand(0);
13915       SDValue Op2Scalar;
13916       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13917         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13918       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13919         Op2Scalar = Op2.getOperand(0);
13920       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13921         SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13922                                         Op1Scalar.getValueType(),
13923                                         Cond, Op1Scalar, Op2Scalar);
13924         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13925           return DAG.getBitcast(VT, newSelect);
13926         SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13927         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13928                            DAG.getIntPtrConstant(0, DL));
13929     }
13930   }
13931
13932   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13933     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13934     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13935                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13936     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13937                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13938     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13939                                     Cond, Op1, Op2);
13940     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13941   }
13942
13943   if (Cond.getOpcode() == ISD::SETCC) {
13944     SDValue NewCond = LowerSETCC(Cond, DAG);
13945     if (NewCond.getNode())
13946       Cond = NewCond;
13947   }
13948
13949   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13950   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13951   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13952   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13953   if (Cond.getOpcode() == X86ISD::SETCC &&
13954       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13955       isZero(Cond.getOperand(1).getOperand(1))) {
13956     SDValue Cmp = Cond.getOperand(1);
13957
13958     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13959
13960     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13961         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13962       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13963
13964       SDValue CmpOp0 = Cmp.getOperand(0);
13965       // Apply further optimizations for special cases
13966       // (select (x != 0), -1, 0) -> neg & sbb
13967       // (select (x == 0), 0, -1) -> neg & sbb
13968       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13969         if (YC->isNullValue() &&
13970             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13971           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13972           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13973                                     DAG.getConstant(0, DL,
13974                                                     CmpOp0.getValueType()),
13975                                     CmpOp0);
13976           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13977                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13978                                     SDValue(Neg.getNode(), 1));
13979           return Res;
13980         }
13981
13982       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13983                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13984       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13985
13986       SDValue Res =   // Res = 0 or -1.
13987         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13988                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13989
13990       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13991         Res = DAG.getNOT(DL, Res, Res.getValueType());
13992
13993       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13994       if (!N2C || !N2C->isNullValue())
13995         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13996       return Res;
13997     }
13998   }
13999
14000   // Look past (and (setcc_carry (cmp ...)), 1).
14001   if (Cond.getOpcode() == ISD::AND &&
14002       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14003     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14004     if (C && C->getAPIntValue() == 1)
14005       Cond = Cond.getOperand(0);
14006   }
14007
14008   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14009   // setting operand in place of the X86ISD::SETCC.
14010   unsigned CondOpcode = Cond.getOpcode();
14011   if (CondOpcode == X86ISD::SETCC ||
14012       CondOpcode == X86ISD::SETCC_CARRY) {
14013     CC = Cond.getOperand(0);
14014
14015     SDValue Cmp = Cond.getOperand(1);
14016     unsigned Opc = Cmp.getOpcode();
14017     MVT VT = Op.getSimpleValueType();
14018
14019     bool IllegalFPCMov = false;
14020     if (VT.isFloatingPoint() && !VT.isVector() &&
14021         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14022       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14023
14024     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14025         Opc == X86ISD::BT) { // FIXME
14026       Cond = Cmp;
14027       addTest = false;
14028     }
14029   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14030              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14031              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14032               Cond.getOperand(0).getValueType() != MVT::i8)) {
14033     SDValue LHS = Cond.getOperand(0);
14034     SDValue RHS = Cond.getOperand(1);
14035     unsigned X86Opcode;
14036     unsigned X86Cond;
14037     SDVTList VTs;
14038     switch (CondOpcode) {
14039     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14040     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14041     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14042     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14043     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14044     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14045     default: llvm_unreachable("unexpected overflowing operator");
14046     }
14047     if (CondOpcode == ISD::UMULO)
14048       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14049                           MVT::i32);
14050     else
14051       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14052
14053     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14054
14055     if (CondOpcode == ISD::UMULO)
14056       Cond = X86Op.getValue(2);
14057     else
14058       Cond = X86Op.getValue(1);
14059
14060     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14061     addTest = false;
14062   }
14063
14064   if (addTest) {
14065     // Look pass the truncate if the high bits are known zero.
14066     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14067         Cond = Cond.getOperand(0);
14068
14069     // We know the result of AND is compared against zero. Try to match
14070     // it to BT.
14071     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14072       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14073       if (NewSetCC.getNode()) {
14074         CC = NewSetCC.getOperand(0);
14075         Cond = NewSetCC.getOperand(1);
14076         addTest = false;
14077       }
14078     }
14079   }
14080
14081   if (addTest) {
14082     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14083     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14084   }
14085
14086   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14087   // a <  b ?  0 : -1 -> RES = setcc_carry
14088   // a >= b ? -1 :  0 -> RES = setcc_carry
14089   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14090   if (Cond.getOpcode() == X86ISD::SUB) {
14091     Cond = ConvertCmpIfNecessary(Cond, DAG);
14092     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14093
14094     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14095         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14096       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14097                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14098                                 Cond);
14099       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14100         return DAG.getNOT(DL, Res, Res.getValueType());
14101       return Res;
14102     }
14103   }
14104
14105   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14106   // widen the cmov and push the truncate through. This avoids introducing a new
14107   // branch during isel and doesn't add any extensions.
14108   if (Op.getValueType() == MVT::i8 &&
14109       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14110     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14111     if (T1.getValueType() == T2.getValueType() &&
14112         // Blacklist CopyFromReg to avoid partial register stalls.
14113         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14114       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14115       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14116       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14117     }
14118   }
14119
14120   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14121   // condition is true.
14122   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14123   SDValue Ops[] = { Op2, Op1, CC, Cond };
14124   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14125 }
14126
14127 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14128                                        const X86Subtarget *Subtarget,
14129                                        SelectionDAG &DAG) {
14130   MVT VT = Op->getSimpleValueType(0);
14131   SDValue In = Op->getOperand(0);
14132   MVT InVT = In.getSimpleValueType();
14133   MVT VTElt = VT.getVectorElementType();
14134   MVT InVTElt = InVT.getVectorElementType();
14135   SDLoc dl(Op);
14136
14137   // SKX processor
14138   if ((InVTElt == MVT::i1) &&
14139       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14140         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14141
14142        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14143         VTElt.getSizeInBits() <= 16)) ||
14144
14145        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14146         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14147
14148        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14149         VTElt.getSizeInBits() >= 32))))
14150     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14151
14152   unsigned int NumElts = VT.getVectorNumElements();
14153
14154   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14155     return SDValue();
14156
14157   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14158     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14159       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14160     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14161   }
14162
14163   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14164   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14165   SDValue NegOne =
14166    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14167                    ExtVT);
14168   SDValue Zero =
14169    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14170
14171   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14172   if (VT.is512BitVector())
14173     return V;
14174   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14175 }
14176
14177 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14178                                              const X86Subtarget *Subtarget,
14179                                              SelectionDAG &DAG) {
14180   SDValue In = Op->getOperand(0);
14181   MVT VT = Op->getSimpleValueType(0);
14182   MVT InVT = In.getSimpleValueType();
14183   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14184
14185   MVT InSVT = InVT.getScalarType();
14186   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14187
14188   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14189     return SDValue();
14190   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14191     return SDValue();
14192
14193   SDLoc dl(Op);
14194
14195   // SSE41 targets can use the pmovsx* instructions directly.
14196   if (Subtarget->hasSSE41())
14197     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14198
14199   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14200   SDValue Curr = In;
14201   MVT CurrVT = InVT;
14202
14203   // As SRAI is only available on i16/i32 types, we expand only up to i32
14204   // and handle i64 separately.
14205   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14206     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14207     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14208     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14209     Curr = DAG.getBitcast(CurrVT, Curr);
14210   }
14211
14212   SDValue SignExt = Curr;
14213   if (CurrVT != InVT) {
14214     unsigned SignExtShift =
14215         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14216     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14217                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14218   }
14219
14220   if (CurrVT == VT)
14221     return SignExt;
14222
14223   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14224     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14225                                DAG.getConstant(31, dl, MVT::i8));
14226     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14227     return DAG.getBitcast(VT, Ext);
14228   }
14229
14230   return SDValue();
14231 }
14232
14233 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14234                                 SelectionDAG &DAG) {
14235   MVT VT = Op->getSimpleValueType(0);
14236   SDValue In = Op->getOperand(0);
14237   MVT InVT = In.getSimpleValueType();
14238   SDLoc dl(Op);
14239
14240   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14241     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14242
14243   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14244       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14245       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14246     return SDValue();
14247
14248   if (Subtarget->hasInt256())
14249     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14250
14251   // Optimize vectors in AVX mode
14252   // Sign extend  v8i16 to v8i32 and
14253   //              v4i32 to v4i64
14254   //
14255   // Divide input vector into two parts
14256   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14257   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14258   // concat the vectors to original VT
14259
14260   unsigned NumElems = InVT.getVectorNumElements();
14261   SDValue Undef = DAG.getUNDEF(InVT);
14262
14263   SmallVector<int,8> ShufMask1(NumElems, -1);
14264   for (unsigned i = 0; i != NumElems/2; ++i)
14265     ShufMask1[i] = i;
14266
14267   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14268
14269   SmallVector<int,8> ShufMask2(NumElems, -1);
14270   for (unsigned i = 0; i != NumElems/2; ++i)
14271     ShufMask2[i] = i + NumElems/2;
14272
14273   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14274
14275   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14276                                 VT.getVectorNumElements()/2);
14277
14278   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14279   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14280
14281   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14282 }
14283
14284 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14285 // may emit an illegal shuffle but the expansion is still better than scalar
14286 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14287 // we'll emit a shuffle and a arithmetic shift.
14288 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14289 // TODO: It is possible to support ZExt by zeroing the undef values during
14290 // the shuffle phase or after the shuffle.
14291 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14292                                  SelectionDAG &DAG) {
14293   MVT RegVT = Op.getSimpleValueType();
14294   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14295   assert(RegVT.isInteger() &&
14296          "We only custom lower integer vector sext loads.");
14297
14298   // Nothing useful we can do without SSE2 shuffles.
14299   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14300
14301   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14302   SDLoc dl(Ld);
14303   EVT MemVT = Ld->getMemoryVT();
14304   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14305   unsigned RegSz = RegVT.getSizeInBits();
14306
14307   ISD::LoadExtType Ext = Ld->getExtensionType();
14308
14309   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14310          && "Only anyext and sext are currently implemented.");
14311   assert(MemVT != RegVT && "Cannot extend to the same type");
14312   assert(MemVT.isVector() && "Must load a vector from memory");
14313
14314   unsigned NumElems = RegVT.getVectorNumElements();
14315   unsigned MemSz = MemVT.getSizeInBits();
14316   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14317
14318   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14319     // The only way in which we have a legal 256-bit vector result but not the
14320     // integer 256-bit operations needed to directly lower a sextload is if we
14321     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14322     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14323     // correctly legalized. We do this late to allow the canonical form of
14324     // sextload to persist throughout the rest of the DAG combiner -- it wants
14325     // to fold together any extensions it can, and so will fuse a sign_extend
14326     // of an sextload into a sextload targeting a wider value.
14327     SDValue Load;
14328     if (MemSz == 128) {
14329       // Just switch this to a normal load.
14330       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14331                                        "it must be a legal 128-bit vector "
14332                                        "type!");
14333       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14334                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14335                   Ld->isInvariant(), Ld->getAlignment());
14336     } else {
14337       assert(MemSz < 128 &&
14338              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14339       // Do an sext load to a 128-bit vector type. We want to use the same
14340       // number of elements, but elements half as wide. This will end up being
14341       // recursively lowered by this routine, but will succeed as we definitely
14342       // have all the necessary features if we're using AVX1.
14343       EVT HalfEltVT =
14344           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14345       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14346       Load =
14347           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14348                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14349                          Ld->isNonTemporal(), Ld->isInvariant(),
14350                          Ld->getAlignment());
14351     }
14352
14353     // Replace chain users with the new chain.
14354     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14355     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14356
14357     // Finally, do a normal sign-extend to the desired register.
14358     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14359   }
14360
14361   // All sizes must be a power of two.
14362   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14363          "Non-power-of-two elements are not custom lowered!");
14364
14365   // Attempt to load the original value using scalar loads.
14366   // Find the largest scalar type that divides the total loaded size.
14367   MVT SclrLoadTy = MVT::i8;
14368   for (MVT Tp : MVT::integer_valuetypes()) {
14369     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14370       SclrLoadTy = Tp;
14371     }
14372   }
14373
14374   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14375   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14376       (64 <= MemSz))
14377     SclrLoadTy = MVT::f64;
14378
14379   // Calculate the number of scalar loads that we need to perform
14380   // in order to load our vector from memory.
14381   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14382
14383   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14384          "Can only lower sext loads with a single scalar load!");
14385
14386   unsigned loadRegZize = RegSz;
14387   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14388     loadRegZize = 128;
14389
14390   // Represent our vector as a sequence of elements which are the
14391   // largest scalar that we can load.
14392   EVT LoadUnitVecVT = EVT::getVectorVT(
14393       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14394
14395   // Represent the data using the same element type that is stored in
14396   // memory. In practice, we ''widen'' MemVT.
14397   EVT WideVecVT =
14398       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14399                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14400
14401   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14402          "Invalid vector type");
14403
14404   // We can't shuffle using an illegal type.
14405   assert(TLI.isTypeLegal(WideVecVT) &&
14406          "We only lower types that form legal widened vector types");
14407
14408   SmallVector<SDValue, 8> Chains;
14409   SDValue Ptr = Ld->getBasePtr();
14410   SDValue Increment =
14411       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14412   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14413
14414   for (unsigned i = 0; i < NumLoads; ++i) {
14415     // Perform a single load.
14416     SDValue ScalarLoad =
14417         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14418                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14419                     Ld->getAlignment());
14420     Chains.push_back(ScalarLoad.getValue(1));
14421     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14422     // another round of DAGCombining.
14423     if (i == 0)
14424       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14425     else
14426       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14427                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14428
14429     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14430   }
14431
14432   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14433
14434   // Bitcast the loaded value to a vector of the original element type, in
14435   // the size of the target vector type.
14436   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14437   unsigned SizeRatio = RegSz / MemSz;
14438
14439   if (Ext == ISD::SEXTLOAD) {
14440     // If we have SSE4.1, we can directly emit a VSEXT node.
14441     if (Subtarget->hasSSE41()) {
14442       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14443       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14444       return Sext;
14445     }
14446
14447     // Otherwise we'll shuffle the small elements in the high bits of the
14448     // larger type and perform an arithmetic shift. If the shift is not legal
14449     // it's better to scalarize.
14450     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14451            "We can't implement a sext load without an arithmetic right shift!");
14452
14453     // Redistribute the loaded elements into the different locations.
14454     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14455     for (unsigned i = 0; i != NumElems; ++i)
14456       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14457
14458     SDValue Shuff = DAG.getVectorShuffle(
14459         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14460
14461     Shuff = DAG.getBitcast(RegVT, Shuff);
14462
14463     // Build the arithmetic shift.
14464     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14465                    MemVT.getVectorElementType().getSizeInBits();
14466     Shuff =
14467         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14468                     DAG.getConstant(Amt, dl, RegVT));
14469
14470     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14471     return Shuff;
14472   }
14473
14474   // Redistribute the loaded elements into the different locations.
14475   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14476   for (unsigned i = 0; i != NumElems; ++i)
14477     ShuffleVec[i * SizeRatio] = i;
14478
14479   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14480                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14481
14482   // Bitcast to the requested type.
14483   Shuff = DAG.getBitcast(RegVT, Shuff);
14484   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14485   return Shuff;
14486 }
14487
14488 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14489 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14490 // from the AND / OR.
14491 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14492   Opc = Op.getOpcode();
14493   if (Opc != ISD::OR && Opc != ISD::AND)
14494     return false;
14495   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14496           Op.getOperand(0).hasOneUse() &&
14497           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14498           Op.getOperand(1).hasOneUse());
14499 }
14500
14501 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14502 // 1 and that the SETCC node has a single use.
14503 static bool isXor1OfSetCC(SDValue Op) {
14504   if (Op.getOpcode() != ISD::XOR)
14505     return false;
14506   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14507   if (N1C && N1C->getAPIntValue() == 1) {
14508     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14509       Op.getOperand(0).hasOneUse();
14510   }
14511   return false;
14512 }
14513
14514 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14515   bool addTest = true;
14516   SDValue Chain = Op.getOperand(0);
14517   SDValue Cond  = Op.getOperand(1);
14518   SDValue Dest  = Op.getOperand(2);
14519   SDLoc dl(Op);
14520   SDValue CC;
14521   bool Inverted = false;
14522
14523   if (Cond.getOpcode() == ISD::SETCC) {
14524     // Check for setcc([su]{add,sub,mul}o == 0).
14525     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14526         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14527         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14528         Cond.getOperand(0).getResNo() == 1 &&
14529         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14530          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14531          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14532          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14533          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14534          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14535       Inverted = true;
14536       Cond = Cond.getOperand(0);
14537     } else {
14538       SDValue NewCond = LowerSETCC(Cond, DAG);
14539       if (NewCond.getNode())
14540         Cond = NewCond;
14541     }
14542   }
14543 #if 0
14544   // FIXME: LowerXALUO doesn't handle these!!
14545   else if (Cond.getOpcode() == X86ISD::ADD  ||
14546            Cond.getOpcode() == X86ISD::SUB  ||
14547            Cond.getOpcode() == X86ISD::SMUL ||
14548            Cond.getOpcode() == X86ISD::UMUL)
14549     Cond = LowerXALUO(Cond, DAG);
14550 #endif
14551
14552   // Look pass (and (setcc_carry (cmp ...)), 1).
14553   if (Cond.getOpcode() == ISD::AND &&
14554       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14555     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14556     if (C && C->getAPIntValue() == 1)
14557       Cond = Cond.getOperand(0);
14558   }
14559
14560   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14561   // setting operand in place of the X86ISD::SETCC.
14562   unsigned CondOpcode = Cond.getOpcode();
14563   if (CondOpcode == X86ISD::SETCC ||
14564       CondOpcode == X86ISD::SETCC_CARRY) {
14565     CC = Cond.getOperand(0);
14566
14567     SDValue Cmp = Cond.getOperand(1);
14568     unsigned Opc = Cmp.getOpcode();
14569     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14570     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14571       Cond = Cmp;
14572       addTest = false;
14573     } else {
14574       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14575       default: break;
14576       case X86::COND_O:
14577       case X86::COND_B:
14578         // These can only come from an arithmetic instruction with overflow,
14579         // e.g. SADDO, UADDO.
14580         Cond = Cond.getNode()->getOperand(1);
14581         addTest = false;
14582         break;
14583       }
14584     }
14585   }
14586   CondOpcode = Cond.getOpcode();
14587   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14588       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14589       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14590        Cond.getOperand(0).getValueType() != MVT::i8)) {
14591     SDValue LHS = Cond.getOperand(0);
14592     SDValue RHS = Cond.getOperand(1);
14593     unsigned X86Opcode;
14594     unsigned X86Cond;
14595     SDVTList VTs;
14596     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14597     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14598     // X86ISD::INC).
14599     switch (CondOpcode) {
14600     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14601     case ISD::SADDO:
14602       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14603         if (C->isOne()) {
14604           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14605           break;
14606         }
14607       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14608     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14609     case ISD::SSUBO:
14610       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14611         if (C->isOne()) {
14612           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14613           break;
14614         }
14615       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14616     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14617     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14618     default: llvm_unreachable("unexpected overflowing operator");
14619     }
14620     if (Inverted)
14621       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14622     if (CondOpcode == ISD::UMULO)
14623       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14624                           MVT::i32);
14625     else
14626       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14627
14628     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14629
14630     if (CondOpcode == ISD::UMULO)
14631       Cond = X86Op.getValue(2);
14632     else
14633       Cond = X86Op.getValue(1);
14634
14635     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14636     addTest = false;
14637   } else {
14638     unsigned CondOpc;
14639     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14640       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14641       if (CondOpc == ISD::OR) {
14642         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14643         // two branches instead of an explicit OR instruction with a
14644         // separate test.
14645         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14646             isX86LogicalCmp(Cmp)) {
14647           CC = Cond.getOperand(0).getOperand(0);
14648           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14649                               Chain, Dest, CC, Cmp);
14650           CC = Cond.getOperand(1).getOperand(0);
14651           Cond = Cmp;
14652           addTest = false;
14653         }
14654       } else { // ISD::AND
14655         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14656         // two branches instead of an explicit AND instruction with a
14657         // separate test. However, we only do this if this block doesn't
14658         // have a fall-through edge, because this requires an explicit
14659         // jmp when the condition is false.
14660         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14661             isX86LogicalCmp(Cmp) &&
14662             Op.getNode()->hasOneUse()) {
14663           X86::CondCode CCode =
14664             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14665           CCode = X86::GetOppositeBranchCondition(CCode);
14666           CC = DAG.getConstant(CCode, dl, MVT::i8);
14667           SDNode *User = *Op.getNode()->use_begin();
14668           // Look for an unconditional branch following this conditional branch.
14669           // We need this because we need to reverse the successors in order
14670           // to implement FCMP_OEQ.
14671           if (User->getOpcode() == ISD::BR) {
14672             SDValue FalseBB = User->getOperand(1);
14673             SDNode *NewBR =
14674               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14675             assert(NewBR == User);
14676             (void)NewBR;
14677             Dest = FalseBB;
14678
14679             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14680                                 Chain, Dest, CC, Cmp);
14681             X86::CondCode CCode =
14682               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14683             CCode = X86::GetOppositeBranchCondition(CCode);
14684             CC = DAG.getConstant(CCode, dl, MVT::i8);
14685             Cond = Cmp;
14686             addTest = false;
14687           }
14688         }
14689       }
14690     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14691       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14692       // It should be transformed during dag combiner except when the condition
14693       // is set by a arithmetics with overflow node.
14694       X86::CondCode CCode =
14695         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14696       CCode = X86::GetOppositeBranchCondition(CCode);
14697       CC = DAG.getConstant(CCode, dl, MVT::i8);
14698       Cond = Cond.getOperand(0).getOperand(1);
14699       addTest = false;
14700     } else if (Cond.getOpcode() == ISD::SETCC &&
14701                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14702       // For FCMP_OEQ, we can emit
14703       // two branches instead of an explicit AND instruction with a
14704       // separate test. However, we only do this if this block doesn't
14705       // have a fall-through edge, because this requires an explicit
14706       // jmp when the condition is false.
14707       if (Op.getNode()->hasOneUse()) {
14708         SDNode *User = *Op.getNode()->use_begin();
14709         // Look for an unconditional branch following this conditional branch.
14710         // We need this because we need to reverse the successors in order
14711         // to implement FCMP_OEQ.
14712         if (User->getOpcode() == ISD::BR) {
14713           SDValue FalseBB = User->getOperand(1);
14714           SDNode *NewBR =
14715             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14716           assert(NewBR == User);
14717           (void)NewBR;
14718           Dest = FalseBB;
14719
14720           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14721                                     Cond.getOperand(0), Cond.getOperand(1));
14722           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14723           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14724           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14725                               Chain, Dest, CC, Cmp);
14726           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14727           Cond = Cmp;
14728           addTest = false;
14729         }
14730       }
14731     } else if (Cond.getOpcode() == ISD::SETCC &&
14732                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14733       // For FCMP_UNE, we can emit
14734       // two branches instead of an explicit AND instruction with a
14735       // separate test. However, we only do this if this block doesn't
14736       // have a fall-through edge, because this requires an explicit
14737       // jmp when the condition is false.
14738       if (Op.getNode()->hasOneUse()) {
14739         SDNode *User = *Op.getNode()->use_begin();
14740         // Look for an unconditional branch following this conditional branch.
14741         // We need this because we need to reverse the successors in order
14742         // to implement FCMP_UNE.
14743         if (User->getOpcode() == ISD::BR) {
14744           SDValue FalseBB = User->getOperand(1);
14745           SDNode *NewBR =
14746             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14747           assert(NewBR == User);
14748           (void)NewBR;
14749
14750           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14751                                     Cond.getOperand(0), Cond.getOperand(1));
14752           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14753           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14754           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14755                               Chain, Dest, CC, Cmp);
14756           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14757           Cond = Cmp;
14758           addTest = false;
14759           Dest = FalseBB;
14760         }
14761       }
14762     }
14763   }
14764
14765   if (addTest) {
14766     // Look pass the truncate if the high bits are known zero.
14767     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14768         Cond = Cond.getOperand(0);
14769
14770     // We know the result of AND is compared against zero. Try to match
14771     // it to BT.
14772     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14773       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14774       if (NewSetCC.getNode()) {
14775         CC = NewSetCC.getOperand(0);
14776         Cond = NewSetCC.getOperand(1);
14777         addTest = false;
14778       }
14779     }
14780   }
14781
14782   if (addTest) {
14783     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14784     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14785     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14786   }
14787   Cond = ConvertCmpIfNecessary(Cond, DAG);
14788   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14789                      Chain, Dest, CC, Cond);
14790 }
14791
14792 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14793 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14794 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14795 // that the guard pages used by the OS virtual memory manager are allocated in
14796 // correct sequence.
14797 SDValue
14798 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14799                                            SelectionDAG &DAG) const {
14800   MachineFunction &MF = DAG.getMachineFunction();
14801   bool SplitStack = MF.shouldSplitStack();
14802   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14803                SplitStack;
14804   SDLoc dl(Op);
14805
14806   if (!Lower) {
14807     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14808     SDNode* Node = Op.getNode();
14809
14810     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14811     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14812         " not tell us which reg is the stack pointer!");
14813     EVT VT = Node->getValueType(0);
14814     SDValue Tmp1 = SDValue(Node, 0);
14815     SDValue Tmp2 = SDValue(Node, 1);
14816     SDValue Tmp3 = Node->getOperand(2);
14817     SDValue Chain = Tmp1.getOperand(0);
14818
14819     // Chain the dynamic stack allocation so that it doesn't modify the stack
14820     // pointer when other instructions are using the stack.
14821     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14822         SDLoc(Node));
14823
14824     SDValue Size = Tmp2.getOperand(1);
14825     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14826     Chain = SP.getValue(1);
14827     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14828     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14829     unsigned StackAlign = TFI.getStackAlignment();
14830     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14831     if (Align > StackAlign)
14832       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14833           DAG.getConstant(-(uint64_t)Align, dl, VT));
14834     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14835
14836     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14837         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14838         SDLoc(Node));
14839
14840     SDValue Ops[2] = { Tmp1, Tmp2 };
14841     return DAG.getMergeValues(Ops, dl);
14842   }
14843
14844   // Get the inputs.
14845   SDValue Chain = Op.getOperand(0);
14846   SDValue Size  = Op.getOperand(1);
14847   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14848   EVT VT = Op.getNode()->getValueType(0);
14849
14850   bool Is64Bit = Subtarget->is64Bit();
14851   EVT SPTy = getPointerTy();
14852
14853   if (SplitStack) {
14854     MachineRegisterInfo &MRI = MF.getRegInfo();
14855
14856     if (Is64Bit) {
14857       // The 64 bit implementation of segmented stacks needs to clobber both r10
14858       // r11. This makes it impossible to use it along with nested parameters.
14859       const Function *F = MF.getFunction();
14860
14861       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14862            I != E; ++I)
14863         if (I->hasNestAttr())
14864           report_fatal_error("Cannot use segmented stacks with functions that "
14865                              "have nested arguments.");
14866     }
14867
14868     const TargetRegisterClass *AddrRegClass =
14869       getRegClassFor(getPointerTy());
14870     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14871     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14872     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14873                                 DAG.getRegister(Vreg, SPTy));
14874     SDValue Ops1[2] = { Value, Chain };
14875     return DAG.getMergeValues(Ops1, dl);
14876   } else {
14877     SDValue Flag;
14878     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14879
14880     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14881     Flag = Chain.getValue(1);
14882     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14883
14884     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14885
14886     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14887     unsigned SPReg = RegInfo->getStackRegister();
14888     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14889     Chain = SP.getValue(1);
14890
14891     if (Align) {
14892       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14893                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14894       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14895     }
14896
14897     SDValue Ops1[2] = { SP, Chain };
14898     return DAG.getMergeValues(Ops1, dl);
14899   }
14900 }
14901
14902 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14903   MachineFunction &MF = DAG.getMachineFunction();
14904   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14905
14906   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14907   SDLoc DL(Op);
14908
14909   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14910     // vastart just stores the address of the VarArgsFrameIndex slot into the
14911     // memory location argument.
14912     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14913                                    getPointerTy());
14914     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14915                         MachinePointerInfo(SV), false, false, 0);
14916   }
14917
14918   // __va_list_tag:
14919   //   gp_offset         (0 - 6 * 8)
14920   //   fp_offset         (48 - 48 + 8 * 16)
14921   //   overflow_arg_area (point to parameters coming in memory).
14922   //   reg_save_area
14923   SmallVector<SDValue, 8> MemOps;
14924   SDValue FIN = Op.getOperand(1);
14925   // Store gp_offset
14926   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14927                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14928                                                DL, MVT::i32),
14929                                FIN, MachinePointerInfo(SV), false, false, 0);
14930   MemOps.push_back(Store);
14931
14932   // Store fp_offset
14933   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14934                     FIN, DAG.getIntPtrConstant(4, DL));
14935   Store = DAG.getStore(Op.getOperand(0), DL,
14936                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14937                                        MVT::i32),
14938                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14939   MemOps.push_back(Store);
14940
14941   // Store ptr to overflow_arg_area
14942   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14943                     FIN, DAG.getIntPtrConstant(4, DL));
14944   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14945                                     getPointerTy());
14946   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14947                        MachinePointerInfo(SV, 8),
14948                        false, false, 0);
14949   MemOps.push_back(Store);
14950
14951   // Store ptr to reg_save_area.
14952   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14953                     FIN, DAG.getIntPtrConstant(8, DL));
14954   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14955                                     getPointerTy());
14956   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14957                        MachinePointerInfo(SV, 16), false, false, 0);
14958   MemOps.push_back(Store);
14959   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14960 }
14961
14962 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14963   assert(Subtarget->is64Bit() &&
14964          "LowerVAARG only handles 64-bit va_arg!");
14965   assert((Subtarget->isTargetLinux() ||
14966           Subtarget->isTargetDarwin()) &&
14967           "Unhandled target in LowerVAARG");
14968   assert(Op.getNode()->getNumOperands() == 4);
14969   SDValue Chain = Op.getOperand(0);
14970   SDValue SrcPtr = Op.getOperand(1);
14971   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14972   unsigned Align = Op.getConstantOperandVal(3);
14973   SDLoc dl(Op);
14974
14975   EVT ArgVT = Op.getNode()->getValueType(0);
14976   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14977   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14978   uint8_t ArgMode;
14979
14980   // Decide which area this value should be read from.
14981   // TODO: Implement the AMD64 ABI in its entirety. This simple
14982   // selection mechanism works only for the basic types.
14983   if (ArgVT == MVT::f80) {
14984     llvm_unreachable("va_arg for f80 not yet implemented");
14985   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14986     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14987   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14988     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14989   } else {
14990     llvm_unreachable("Unhandled argument type in LowerVAARG");
14991   }
14992
14993   if (ArgMode == 2) {
14994     // Sanity Check: Make sure using fp_offset makes sense.
14995     assert(!Subtarget->useSoftFloat() &&
14996            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14997                Attribute::NoImplicitFloat)) &&
14998            Subtarget->hasSSE1());
14999   }
15000
15001   // Insert VAARG_64 node into the DAG
15002   // VAARG_64 returns two values: Variable Argument Address, Chain
15003   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15004                        DAG.getConstant(ArgMode, dl, MVT::i8),
15005                        DAG.getConstant(Align, dl, MVT::i32)};
15006   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
15007   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15008                                           VTs, InstOps, MVT::i64,
15009                                           MachinePointerInfo(SV),
15010                                           /*Align=*/0,
15011                                           /*Volatile=*/false,
15012                                           /*ReadMem=*/true,
15013                                           /*WriteMem=*/true);
15014   Chain = VAARG.getValue(1);
15015
15016   // Load the next argument and return it
15017   return DAG.getLoad(ArgVT, dl,
15018                      Chain,
15019                      VAARG,
15020                      MachinePointerInfo(),
15021                      false, false, false, 0);
15022 }
15023
15024 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15025                            SelectionDAG &DAG) {
15026   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15027   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15028   SDValue Chain = Op.getOperand(0);
15029   SDValue DstPtr = Op.getOperand(1);
15030   SDValue SrcPtr = Op.getOperand(2);
15031   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15032   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15033   SDLoc DL(Op);
15034
15035   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15036                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15037                        false, false,
15038                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15039 }
15040
15041 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15042 // amount is a constant. Takes immediate version of shift as input.
15043 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15044                                           SDValue SrcOp, uint64_t ShiftAmt,
15045                                           SelectionDAG &DAG) {
15046   MVT ElementType = VT.getVectorElementType();
15047
15048   // Fold this packed shift into its first operand if ShiftAmt is 0.
15049   if (ShiftAmt == 0)
15050     return SrcOp;
15051
15052   // Check for ShiftAmt >= element width
15053   if (ShiftAmt >= ElementType.getSizeInBits()) {
15054     if (Opc == X86ISD::VSRAI)
15055       ShiftAmt = ElementType.getSizeInBits() - 1;
15056     else
15057       return DAG.getConstant(0, dl, VT);
15058   }
15059
15060   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15061          && "Unknown target vector shift-by-constant node");
15062
15063   // Fold this packed vector shift into a build vector if SrcOp is a
15064   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15065   if (VT == SrcOp.getSimpleValueType() &&
15066       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15067     SmallVector<SDValue, 8> Elts;
15068     unsigned NumElts = SrcOp->getNumOperands();
15069     ConstantSDNode *ND;
15070
15071     switch(Opc) {
15072     default: llvm_unreachable(nullptr);
15073     case X86ISD::VSHLI:
15074       for (unsigned i=0; i!=NumElts; ++i) {
15075         SDValue CurrentOp = SrcOp->getOperand(i);
15076         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15077           Elts.push_back(CurrentOp);
15078           continue;
15079         }
15080         ND = cast<ConstantSDNode>(CurrentOp);
15081         const APInt &C = ND->getAPIntValue();
15082         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15083       }
15084       break;
15085     case X86ISD::VSRLI:
15086       for (unsigned i=0; i!=NumElts; ++i) {
15087         SDValue CurrentOp = SrcOp->getOperand(i);
15088         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15089           Elts.push_back(CurrentOp);
15090           continue;
15091         }
15092         ND = cast<ConstantSDNode>(CurrentOp);
15093         const APInt &C = ND->getAPIntValue();
15094         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15095       }
15096       break;
15097     case X86ISD::VSRAI:
15098       for (unsigned i=0; i!=NumElts; ++i) {
15099         SDValue CurrentOp = SrcOp->getOperand(i);
15100         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15101           Elts.push_back(CurrentOp);
15102           continue;
15103         }
15104         ND = cast<ConstantSDNode>(CurrentOp);
15105         const APInt &C = ND->getAPIntValue();
15106         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15107       }
15108       break;
15109     }
15110
15111     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15112   }
15113
15114   return DAG.getNode(Opc, dl, VT, SrcOp,
15115                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15116 }
15117
15118 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15119 // may or may not be a constant. Takes immediate version of shift as input.
15120 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15121                                    SDValue SrcOp, SDValue ShAmt,
15122                                    SelectionDAG &DAG) {
15123   MVT SVT = ShAmt.getSimpleValueType();
15124   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15125
15126   // Catch shift-by-constant.
15127   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15128     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15129                                       CShAmt->getZExtValue(), DAG);
15130
15131   // Change opcode to non-immediate version
15132   switch (Opc) {
15133     default: llvm_unreachable("Unknown target vector shift node");
15134     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15135     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15136     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15137   }
15138
15139   const X86Subtarget &Subtarget =
15140       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15141   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15142       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15143     // Let the shuffle legalizer expand this shift amount node.
15144     SDValue Op0 = ShAmt.getOperand(0);
15145     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15146     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15147   } else {
15148     // Need to build a vector containing shift amount.
15149     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15150     SmallVector<SDValue, 4> ShOps;
15151     ShOps.push_back(ShAmt);
15152     if (SVT == MVT::i32) {
15153       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15154       ShOps.push_back(DAG.getUNDEF(SVT));
15155     }
15156     ShOps.push_back(DAG.getUNDEF(SVT));
15157
15158     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15159     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15160   }
15161
15162   // The return type has to be a 128-bit type with the same element
15163   // type as the input type.
15164   MVT EltVT = VT.getVectorElementType();
15165   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15166
15167   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15168   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15169 }
15170
15171 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15172 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15173 /// necessary casting for \p Mask when lowering masking intrinsics.
15174 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15175                                     SDValue PreservedSrc,
15176                                     const X86Subtarget *Subtarget,
15177                                     SelectionDAG &DAG) {
15178     EVT VT = Op.getValueType();
15179     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15180                                   MVT::i1, VT.getVectorNumElements());
15181     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15182                                      Mask.getValueType().getSizeInBits());
15183     SDLoc dl(Op);
15184
15185     assert(MaskVT.isSimple() && "invalid mask type");
15186
15187     if (isAllOnes(Mask))
15188       return Op;
15189
15190     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15191     // are extracted by EXTRACT_SUBVECTOR.
15192     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15193                                 DAG.getBitcast(BitcastVT, Mask),
15194                                 DAG.getIntPtrConstant(0, dl));
15195
15196     switch (Op.getOpcode()) {
15197       default: break;
15198       case X86ISD::PCMPEQM:
15199       case X86ISD::PCMPGTM:
15200       case X86ISD::CMPM:
15201       case X86ISD::CMPMU:
15202         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15203     }
15204     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15205       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15206     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15207 }
15208
15209 /// \brief Creates an SDNode for a predicated scalar operation.
15210 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15211 /// The mask is comming as MVT::i8 and it should be truncated
15212 /// to MVT::i1 while lowering masking intrinsics.
15213 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15214 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15215 /// a scalar instruction.
15216 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15217                                     SDValue PreservedSrc,
15218                                     const X86Subtarget *Subtarget,
15219                                     SelectionDAG &DAG) {
15220     if (isAllOnes(Mask))
15221       return Op;
15222
15223     EVT VT = Op.getValueType();
15224     SDLoc dl(Op);
15225     // The mask should be of type MVT::i1
15226     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15227
15228     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15229       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15230     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15231 }
15232
15233 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15234 /// function or when returning to a parent frame after catching an exception, we
15235 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15236 /// Here's the math:
15237 ///   RegNodeBase = EntryEBP - RegNodeSize
15238 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15239 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15240 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15241 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15242                                    SDValue EntryEBP) {
15243   MachineFunction &MF = DAG.getMachineFunction();
15244   SDLoc dl;
15245
15246   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15247   MVT PtrVT = TLI.getPointerTy();
15248
15249   // It's possible that the parent function no longer has a personality function
15250   // if the exceptional code was optimized away, in which case we just return
15251   // the incoming EBP.
15252   if (!Fn->hasPersonalityFn())
15253     return EntryEBP;
15254
15255   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15256   // WinEHStatePass for the full struct definition.
15257   int RegNodeSize;
15258   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15259   default:
15260     report_fatal_error("can only recover FP for MSVC EH personality functions");
15261   case EHPersonality::MSVC_X86SEH: RegNodeSize = 24; break;
15262   case EHPersonality::MSVC_CXX: RegNodeSize = 16; break;
15263   }
15264
15265   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15266   // registration.
15267   MCSymbol *OffsetSym =
15268       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15269           GlobalValue::getRealLinkageName(Fn->getName()));
15270   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15271   SDValue RegNodeFrameOffset =
15272       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15273
15274   // RegNodeBase = EntryEBP - RegNodeSize
15275   // ParentFP = RegNodeBase - RegNodeFrameOffset
15276   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15277                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15278   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15279 }
15280
15281 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15282                                        SelectionDAG &DAG) {
15283   SDLoc dl(Op);
15284   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15285   EVT VT = Op.getValueType();
15286   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15287   if (IntrData) {
15288     switch(IntrData->Type) {
15289     case INTR_TYPE_1OP:
15290       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15291     case INTR_TYPE_2OP:
15292       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15293         Op.getOperand(2));
15294     case INTR_TYPE_3OP:
15295       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15296         Op.getOperand(2), Op.getOperand(3));
15297     case INTR_TYPE_4OP:
15298       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15299         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15300     case INTR_TYPE_1OP_MASK_RM: {
15301       SDValue Src = Op.getOperand(1);
15302       SDValue PassThru = Op.getOperand(2);
15303       SDValue Mask = Op.getOperand(3);
15304       SDValue RoundingMode;
15305       if (Op.getNumOperands() == 4)
15306         RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15307       else
15308         RoundingMode = Op.getOperand(4);
15309       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15310       if (IntrWithRoundingModeOpcode != 0) {
15311         unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15312         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15313           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15314                                       dl, Op.getValueType(), Src, RoundingMode),
15315                                       Mask, PassThru, Subtarget, DAG);
15316       }
15317       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15318                                               RoundingMode),
15319                                   Mask, PassThru, Subtarget, DAG);
15320     }
15321     case INTR_TYPE_1OP_MASK: {
15322       SDValue Src = Op.getOperand(1);
15323       SDValue Passthru = Op.getOperand(2);
15324       SDValue Mask = Op.getOperand(3);
15325       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15326                                   Mask, Passthru, Subtarget, DAG);
15327     }
15328     case INTR_TYPE_SCALAR_MASK_RM: {
15329       SDValue Src1 = Op.getOperand(1);
15330       SDValue Src2 = Op.getOperand(2);
15331       SDValue Src0 = Op.getOperand(3);
15332       SDValue Mask = Op.getOperand(4);
15333       // There are 2 kinds of intrinsics in this group:
15334       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15335       // (2) With rounding mode and sae - 7 operands.
15336       if (Op.getNumOperands() == 6) {
15337         SDValue Sae  = Op.getOperand(5);
15338         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15339         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15340                                                 Sae),
15341                                     Mask, Src0, Subtarget, DAG);
15342       }
15343       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15344       SDValue RoundingMode  = Op.getOperand(5);
15345       SDValue Sae  = Op.getOperand(6);
15346       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15347                                               RoundingMode, Sae),
15348                                   Mask, Src0, Subtarget, DAG);
15349     }
15350     case INTR_TYPE_2OP_MASK: {
15351       SDValue Src1 = Op.getOperand(1);
15352       SDValue Src2 = Op.getOperand(2);
15353       SDValue PassThru = Op.getOperand(3);
15354       SDValue Mask = Op.getOperand(4);
15355       // We specify 2 possible opcodes for intrinsics with rounding modes.
15356       // First, we check if the intrinsic may have non-default rounding mode,
15357       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15358       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15359       if (IntrWithRoundingModeOpcode != 0) {
15360         SDValue Rnd = Op.getOperand(5);
15361         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15362         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15363           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15364                                       dl, Op.getValueType(),
15365                                       Src1, Src2, Rnd),
15366                                       Mask, PassThru, Subtarget, DAG);
15367         }
15368       }
15369       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15370                                               Src1,Src2),
15371                                   Mask, PassThru, Subtarget, DAG);
15372     }
15373     case INTR_TYPE_2OP_MASK_RM: {
15374       SDValue Src1 = Op.getOperand(1);
15375       SDValue Src2 = Op.getOperand(2);
15376       SDValue PassThru = Op.getOperand(3);
15377       SDValue Mask = Op.getOperand(4);
15378       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15379       // First, we check if the intrinsic have rounding mode (6 operands),
15380       // if not, we set rounding mode to "current".
15381       SDValue Rnd;
15382       if (Op.getNumOperands() == 6)
15383         Rnd = Op.getOperand(5);
15384       else 
15385         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15386       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15387                                               Src1, Src2, Rnd),
15388                                   Mask, PassThru, Subtarget, DAG);
15389     }
15390     case INTR_TYPE_3OP_MASK: {
15391       SDValue Src1 = Op.getOperand(1);
15392       SDValue Src2 = Op.getOperand(2);
15393       SDValue Src3 = Op.getOperand(3);
15394       SDValue PassThru = Op.getOperand(4);
15395       SDValue Mask = Op.getOperand(5);
15396       // We specify 2 possible opcodes for intrinsics with rounding modes.
15397       // First, we check if the intrinsic may have non-default rounding mode,
15398       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15399       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15400       if (IntrWithRoundingModeOpcode != 0) {
15401         SDValue Rnd = Op.getOperand(6);
15402         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15403         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15404           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15405                                       dl, Op.getValueType(),
15406                                       Src1, Src2, Src3, Rnd),
15407                                       Mask, PassThru, Subtarget, DAG);
15408         }
15409       }
15410       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15411                                               Src1, Src2, Src3),
15412                                   Mask, PassThru, Subtarget, DAG);
15413     }
15414     case VPERM_3OP_MASKZ: 
15415     case VPERM_3OP_MASK:
15416     case FMA_OP_MASK3:
15417     case FMA_OP_MASKZ:
15418     case FMA_OP_MASK: {
15419       SDValue Src1 = Op.getOperand(1);
15420       SDValue Src2 = Op.getOperand(2);
15421       SDValue Src3 = Op.getOperand(3);
15422       SDValue Mask = Op.getOperand(4);
15423       EVT VT = Op.getValueType();
15424       SDValue PassThru = SDValue();
15425
15426       // set PassThru element
15427       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15428         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15429       else if (IntrData->Type == FMA_OP_MASK3)
15430         PassThru = Src3;
15431       else
15432         PassThru = Src1;
15433
15434       // We specify 2 possible opcodes for intrinsics with rounding modes.
15435       // First, we check if the intrinsic may have non-default rounding mode,
15436       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15437       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15438       if (IntrWithRoundingModeOpcode != 0) {
15439         SDValue Rnd = Op.getOperand(5);
15440         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15441             X86::STATIC_ROUNDING::CUR_DIRECTION)
15442           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15443                                                   dl, Op.getValueType(),
15444                                                   Src1, Src2, Src3, Rnd),
15445                                       Mask, PassThru, Subtarget, DAG);
15446       }
15447       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15448                                               dl, Op.getValueType(),
15449                                               Src1, Src2, Src3),
15450                                   Mask, PassThru, Subtarget, DAG);
15451     }
15452     case CMP_MASK:
15453     case CMP_MASK_CC: {
15454       // Comparison intrinsics with masks.
15455       // Example of transformation:
15456       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15457       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15458       // (i8 (bitcast
15459       //   (v8i1 (insert_subvector undef,
15460       //           (v2i1 (and (PCMPEQM %a, %b),
15461       //                      (extract_subvector
15462       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15463       EVT VT = Op.getOperand(1).getValueType();
15464       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15465                                     VT.getVectorNumElements());
15466       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15467       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15468                                        Mask.getValueType().getSizeInBits());
15469       SDValue Cmp;
15470       if (IntrData->Type == CMP_MASK_CC) {
15471         SDValue CC = Op.getOperand(3);
15472         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15473         // We specify 2 possible opcodes for intrinsics with rounding modes.
15474         // First, we check if the intrinsic may have non-default rounding mode,
15475         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15476         if (IntrData->Opc1 != 0) {
15477           SDValue Rnd = Op.getOperand(5);
15478           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15479               X86::STATIC_ROUNDING::CUR_DIRECTION)
15480             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15481                               Op.getOperand(2), CC, Rnd);
15482         }
15483         //default rounding mode
15484         if(!Cmp.getNode())
15485             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15486                               Op.getOperand(2), CC);
15487
15488       } else {
15489         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15490         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15491                           Op.getOperand(2));
15492       }
15493       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15494                                              DAG.getTargetConstant(0, dl,
15495                                                                    MaskVT),
15496                                              Subtarget, DAG);
15497       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15498                                 DAG.getUNDEF(BitcastVT), CmpMask,
15499                                 DAG.getIntPtrConstant(0, dl));
15500       return DAG.getBitcast(Op.getValueType(), Res);
15501     }
15502     case COMI: { // Comparison intrinsics
15503       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15504       SDValue LHS = Op.getOperand(1);
15505       SDValue RHS = Op.getOperand(2);
15506       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15507       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15508       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15509       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15510                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15511       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15512     }
15513     case VSHIFT:
15514       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15515                                  Op.getOperand(1), Op.getOperand(2), DAG);
15516     case VSHIFT_MASK:
15517       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15518                                                       Op.getSimpleValueType(),
15519                                                       Op.getOperand(1),
15520                                                       Op.getOperand(2), DAG),
15521                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15522                                   DAG);
15523     case COMPRESS_EXPAND_IN_REG: {
15524       SDValue Mask = Op.getOperand(3);
15525       SDValue DataToCompress = Op.getOperand(1);
15526       SDValue PassThru = Op.getOperand(2);
15527       if (isAllOnes(Mask)) // return data as is
15528         return Op.getOperand(1);
15529
15530       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15531                                               DataToCompress),
15532                                   Mask, PassThru, Subtarget, DAG);
15533     }
15534     case BLEND: {
15535       SDValue Mask = Op.getOperand(3);
15536       EVT VT = Op.getValueType();
15537       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15538                                     VT.getVectorNumElements());
15539       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15540                                        Mask.getValueType().getSizeInBits());
15541       SDLoc dl(Op);
15542       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15543                                   DAG.getBitcast(BitcastVT, Mask),
15544                                   DAG.getIntPtrConstant(0, dl));
15545       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15546                          Op.getOperand(2));
15547     }
15548     default:
15549       break;
15550     }
15551   }
15552
15553   switch (IntNo) {
15554   default: return SDValue();    // Don't custom lower most intrinsics.
15555
15556   case Intrinsic::x86_avx2_permd:
15557   case Intrinsic::x86_avx2_permps:
15558     // Operands intentionally swapped. Mask is last operand to intrinsic,
15559     // but second operand for node/instruction.
15560     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15561                        Op.getOperand(2), Op.getOperand(1));
15562
15563   // ptest and testp intrinsics. The intrinsic these come from are designed to
15564   // return an integer value, not just an instruction so lower it to the ptest
15565   // or testp pattern and a setcc for the result.
15566   case Intrinsic::x86_sse41_ptestz:
15567   case Intrinsic::x86_sse41_ptestc:
15568   case Intrinsic::x86_sse41_ptestnzc:
15569   case Intrinsic::x86_avx_ptestz_256:
15570   case Intrinsic::x86_avx_ptestc_256:
15571   case Intrinsic::x86_avx_ptestnzc_256:
15572   case Intrinsic::x86_avx_vtestz_ps:
15573   case Intrinsic::x86_avx_vtestc_ps:
15574   case Intrinsic::x86_avx_vtestnzc_ps:
15575   case Intrinsic::x86_avx_vtestz_pd:
15576   case Intrinsic::x86_avx_vtestc_pd:
15577   case Intrinsic::x86_avx_vtestnzc_pd:
15578   case Intrinsic::x86_avx_vtestz_ps_256:
15579   case Intrinsic::x86_avx_vtestc_ps_256:
15580   case Intrinsic::x86_avx_vtestnzc_ps_256:
15581   case Intrinsic::x86_avx_vtestz_pd_256:
15582   case Intrinsic::x86_avx_vtestc_pd_256:
15583   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15584     bool IsTestPacked = false;
15585     unsigned X86CC;
15586     switch (IntNo) {
15587     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15588     case Intrinsic::x86_avx_vtestz_ps:
15589     case Intrinsic::x86_avx_vtestz_pd:
15590     case Intrinsic::x86_avx_vtestz_ps_256:
15591     case Intrinsic::x86_avx_vtestz_pd_256:
15592       IsTestPacked = true; // Fallthrough
15593     case Intrinsic::x86_sse41_ptestz:
15594     case Intrinsic::x86_avx_ptestz_256:
15595       // ZF = 1
15596       X86CC = X86::COND_E;
15597       break;
15598     case Intrinsic::x86_avx_vtestc_ps:
15599     case Intrinsic::x86_avx_vtestc_pd:
15600     case Intrinsic::x86_avx_vtestc_ps_256:
15601     case Intrinsic::x86_avx_vtestc_pd_256:
15602       IsTestPacked = true; // Fallthrough
15603     case Intrinsic::x86_sse41_ptestc:
15604     case Intrinsic::x86_avx_ptestc_256:
15605       // CF = 1
15606       X86CC = X86::COND_B;
15607       break;
15608     case Intrinsic::x86_avx_vtestnzc_ps:
15609     case Intrinsic::x86_avx_vtestnzc_pd:
15610     case Intrinsic::x86_avx_vtestnzc_ps_256:
15611     case Intrinsic::x86_avx_vtestnzc_pd_256:
15612       IsTestPacked = true; // Fallthrough
15613     case Intrinsic::x86_sse41_ptestnzc:
15614     case Intrinsic::x86_avx_ptestnzc_256:
15615       // ZF and CF = 0
15616       X86CC = X86::COND_A;
15617       break;
15618     }
15619
15620     SDValue LHS = Op.getOperand(1);
15621     SDValue RHS = Op.getOperand(2);
15622     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15623     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15624     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15625     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15626     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15627   }
15628   case Intrinsic::x86_avx512_kortestz_w:
15629   case Intrinsic::x86_avx512_kortestc_w: {
15630     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15631     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15632     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15633     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15634     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15635     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15636     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15637   }
15638
15639   case Intrinsic::x86_sse42_pcmpistria128:
15640   case Intrinsic::x86_sse42_pcmpestria128:
15641   case Intrinsic::x86_sse42_pcmpistric128:
15642   case Intrinsic::x86_sse42_pcmpestric128:
15643   case Intrinsic::x86_sse42_pcmpistrio128:
15644   case Intrinsic::x86_sse42_pcmpestrio128:
15645   case Intrinsic::x86_sse42_pcmpistris128:
15646   case Intrinsic::x86_sse42_pcmpestris128:
15647   case Intrinsic::x86_sse42_pcmpistriz128:
15648   case Intrinsic::x86_sse42_pcmpestriz128: {
15649     unsigned Opcode;
15650     unsigned X86CC;
15651     switch (IntNo) {
15652     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15653     case Intrinsic::x86_sse42_pcmpistria128:
15654       Opcode = X86ISD::PCMPISTRI;
15655       X86CC = X86::COND_A;
15656       break;
15657     case Intrinsic::x86_sse42_pcmpestria128:
15658       Opcode = X86ISD::PCMPESTRI;
15659       X86CC = X86::COND_A;
15660       break;
15661     case Intrinsic::x86_sse42_pcmpistric128:
15662       Opcode = X86ISD::PCMPISTRI;
15663       X86CC = X86::COND_B;
15664       break;
15665     case Intrinsic::x86_sse42_pcmpestric128:
15666       Opcode = X86ISD::PCMPESTRI;
15667       X86CC = X86::COND_B;
15668       break;
15669     case Intrinsic::x86_sse42_pcmpistrio128:
15670       Opcode = X86ISD::PCMPISTRI;
15671       X86CC = X86::COND_O;
15672       break;
15673     case Intrinsic::x86_sse42_pcmpestrio128:
15674       Opcode = X86ISD::PCMPESTRI;
15675       X86CC = X86::COND_O;
15676       break;
15677     case Intrinsic::x86_sse42_pcmpistris128:
15678       Opcode = X86ISD::PCMPISTRI;
15679       X86CC = X86::COND_S;
15680       break;
15681     case Intrinsic::x86_sse42_pcmpestris128:
15682       Opcode = X86ISD::PCMPESTRI;
15683       X86CC = X86::COND_S;
15684       break;
15685     case Intrinsic::x86_sse42_pcmpistriz128:
15686       Opcode = X86ISD::PCMPISTRI;
15687       X86CC = X86::COND_E;
15688       break;
15689     case Intrinsic::x86_sse42_pcmpestriz128:
15690       Opcode = X86ISD::PCMPESTRI;
15691       X86CC = X86::COND_E;
15692       break;
15693     }
15694     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15695     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15696     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15697     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15698                                 DAG.getConstant(X86CC, dl, MVT::i8),
15699                                 SDValue(PCMP.getNode(), 1));
15700     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15701   }
15702
15703   case Intrinsic::x86_sse42_pcmpistri128:
15704   case Intrinsic::x86_sse42_pcmpestri128: {
15705     unsigned Opcode;
15706     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15707       Opcode = X86ISD::PCMPISTRI;
15708     else
15709       Opcode = X86ISD::PCMPESTRI;
15710
15711     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15712     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15713     return DAG.getNode(Opcode, dl, VTs, NewOps);
15714   }
15715
15716   case Intrinsic::x86_seh_lsda: {
15717     // Compute the symbol for the LSDA. We know it'll get emitted later.
15718     MachineFunction &MF = DAG.getMachineFunction();
15719     SDValue Op1 = Op.getOperand(1);
15720     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15721     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15722         GlobalValue::getRealLinkageName(Fn->getName()));
15723
15724     // Generate a simple absolute symbol reference. This intrinsic is only
15725     // supported on 32-bit Windows, which isn't PIC.
15726     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15727     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15728   }
15729
15730   case Intrinsic::x86_seh_recoverfp: {
15731     SDValue FnOp = Op.getOperand(1);
15732     SDValue IncomingFPOp = Op.getOperand(2);
15733     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15734     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15735     if (!Fn)
15736       report_fatal_error(
15737           "llvm.x86.seh.recoverfp must take a function as the first argument");
15738     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15739   }
15740
15741   case Intrinsic::localaddress: {
15742     // Returns one of the stack, base, or frame pointer registers, depending on
15743     // which is used to reference local variables.
15744     MachineFunction &MF = DAG.getMachineFunction();
15745     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15746     unsigned Reg;
15747     if (RegInfo->hasBasePointer(MF))
15748       Reg = RegInfo->getBaseRegister();
15749     else // This function handles the SP or FP case.
15750       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15751     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15752   }
15753   }
15754 }
15755
15756 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15757                               SDValue Src, SDValue Mask, SDValue Base,
15758                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15759                               const X86Subtarget * Subtarget) {
15760   SDLoc dl(Op);
15761   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15762   if (!C)
15763     llvm_unreachable("Invalid scale type");
15764   unsigned ScaleVal = C->getZExtValue();
15765   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15766     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15767
15768   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15769   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15770                              Index.getSimpleValueType().getVectorNumElements());
15771   SDValue MaskInReg;
15772   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15773   if (MaskC)
15774     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15775   else {
15776     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15777                                      Mask.getValueType().getSizeInBits());
15778
15779     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15780     // are extracted by EXTRACT_SUBVECTOR.
15781     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15782                             DAG.getBitcast(BitcastVT, Mask),
15783                             DAG.getIntPtrConstant(0, dl));
15784   }
15785   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15786   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15787   SDValue Segment = DAG.getRegister(0, MVT::i32);
15788   if (Src.getOpcode() == ISD::UNDEF)
15789     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15790   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15791   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15792   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15793   return DAG.getMergeValues(RetOps, dl);
15794 }
15795
15796 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15797                                SDValue Src, SDValue Mask, SDValue Base,
15798                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15799   SDLoc dl(Op);
15800   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15801   if (!C)
15802     llvm_unreachable("Invalid scale type");
15803   unsigned ScaleVal = C->getZExtValue();
15804   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15805     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15806
15807   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15808   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15809   SDValue Segment = DAG.getRegister(0, MVT::i32);
15810   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15811                              Index.getSimpleValueType().getVectorNumElements());
15812   SDValue MaskInReg;
15813   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15814   if (MaskC)
15815     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15816   else {
15817     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15818                                      Mask.getValueType().getSizeInBits());
15819
15820     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15821     // are extracted by EXTRACT_SUBVECTOR.
15822     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15823                             DAG.getBitcast(BitcastVT, Mask),
15824                             DAG.getIntPtrConstant(0, dl));
15825   }
15826   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15827   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15828   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15829   return SDValue(Res, 1);
15830 }
15831
15832 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15833                                SDValue Mask, SDValue Base, SDValue Index,
15834                                SDValue ScaleOp, SDValue Chain) {
15835   SDLoc dl(Op);
15836   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15837   assert(C && "Invalid scale type");
15838   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15839   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15840   SDValue Segment = DAG.getRegister(0, MVT::i32);
15841   EVT MaskVT =
15842     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15843   SDValue MaskInReg;
15844   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15845   if (MaskC)
15846     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15847   else
15848     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15849   //SDVTList VTs = DAG.getVTList(MVT::Other);
15850   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15851   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15852   return SDValue(Res, 0);
15853 }
15854
15855 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15856 // read performance monitor counters (x86_rdpmc).
15857 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15858                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15859                               SmallVectorImpl<SDValue> &Results) {
15860   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15861   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15862   SDValue LO, HI;
15863
15864   // The ECX register is used to select the index of the performance counter
15865   // to read.
15866   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15867                                    N->getOperand(2));
15868   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15869
15870   // Reads the content of a 64-bit performance counter and returns it in the
15871   // registers EDX:EAX.
15872   if (Subtarget->is64Bit()) {
15873     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15874     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15875                             LO.getValue(2));
15876   } else {
15877     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15878     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15879                             LO.getValue(2));
15880   }
15881   Chain = HI.getValue(1);
15882
15883   if (Subtarget->is64Bit()) {
15884     // The EAX register is loaded with the low-order 32 bits. The EDX register
15885     // is loaded with the supported high-order bits of the counter.
15886     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15887                               DAG.getConstant(32, DL, MVT::i8));
15888     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15889     Results.push_back(Chain);
15890     return;
15891   }
15892
15893   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15894   SDValue Ops[] = { LO, HI };
15895   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15896   Results.push_back(Pair);
15897   Results.push_back(Chain);
15898 }
15899
15900 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15901 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15902 // also used to custom lower READCYCLECOUNTER nodes.
15903 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15904                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15905                               SmallVectorImpl<SDValue> &Results) {
15906   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15907   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15908   SDValue LO, HI;
15909
15910   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15911   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15912   // and the EAX register is loaded with the low-order 32 bits.
15913   if (Subtarget->is64Bit()) {
15914     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15915     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15916                             LO.getValue(2));
15917   } else {
15918     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15919     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15920                             LO.getValue(2));
15921   }
15922   SDValue Chain = HI.getValue(1);
15923
15924   if (Opcode == X86ISD::RDTSCP_DAG) {
15925     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15926
15927     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15928     // the ECX register. Add 'ecx' explicitly to the chain.
15929     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15930                                      HI.getValue(2));
15931     // Explicitly store the content of ECX at the location passed in input
15932     // to the 'rdtscp' intrinsic.
15933     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15934                          MachinePointerInfo(), false, false, 0);
15935   }
15936
15937   if (Subtarget->is64Bit()) {
15938     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15939     // the EAX register is loaded with the low-order 32 bits.
15940     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15941                               DAG.getConstant(32, DL, MVT::i8));
15942     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15943     Results.push_back(Chain);
15944     return;
15945   }
15946
15947   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15948   SDValue Ops[] = { LO, HI };
15949   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15950   Results.push_back(Pair);
15951   Results.push_back(Chain);
15952 }
15953
15954 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15955                                      SelectionDAG &DAG) {
15956   SmallVector<SDValue, 2> Results;
15957   SDLoc DL(Op);
15958   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15959                           Results);
15960   return DAG.getMergeValues(Results, DL);
15961 }
15962
15963 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
15964                                     SelectionDAG &DAG) {
15965   MachineFunction &MF = DAG.getMachineFunction();
15966   SDLoc dl(Op);
15967   SDValue Chain = Op.getOperand(0);
15968
15969   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
15970          "using llvm.x86.seh.restoreframe requires a frame pointer");
15971
15972   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15973   MVT VT = TLI.getPointerTy();
15974
15975   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15976   unsigned FrameReg =
15977       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15978   unsigned SPReg = RegInfo->getStackRegister();
15979
15980   // Get incoming EBP.
15981   SDValue IncomingEBP =
15982       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
15983
15984   // Load [EBP-24] into SP.
15985   SDValue SPAddr =
15986       DAG.getNode(ISD::ADD, dl, VT, IncomingEBP, DAG.getConstant(-24, dl, VT));
15987   SDValue NewSP =
15988       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
15989                   false, VT.getScalarSizeInBits() / 8);
15990   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
15991
15992   // FIXME: Restore the base pointer in case of stack realignment!
15993   if (RegInfo->needsStackRealignment(MF))
15994     report_fatal_error("SEH with stack realignment not yet implemented");
15995
15996   // Adjust EBP to point back to the original frame position.
15997   SDValue NewFP = recoverFramePointer(DAG, MF.getFunction(), IncomingEBP);
15998   Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
15999   return Chain;
16000 }
16001
16002 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16003                                       SelectionDAG &DAG) {
16004   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16005
16006   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16007   if (!IntrData) {
16008     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16009       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16010     return SDValue();
16011   }
16012
16013   SDLoc dl(Op);
16014   switch(IntrData->Type) {
16015   default:
16016     llvm_unreachable("Unknown Intrinsic Type");
16017     break;
16018   case RDSEED:
16019   case RDRAND: {
16020     // Emit the node with the right value type.
16021     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16022     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16023
16024     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16025     // Otherwise return the value from Rand, which is always 0, casted to i32.
16026     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16027                       DAG.getConstant(1, dl, Op->getValueType(1)),
16028                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16029                       SDValue(Result.getNode(), 1) };
16030     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16031                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16032                                   Ops);
16033
16034     // Return { result, isValid, chain }.
16035     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16036                        SDValue(Result.getNode(), 2));
16037   }
16038   case GATHER: {
16039   //gather(v1, mask, index, base, scale);
16040     SDValue Chain = Op.getOperand(0);
16041     SDValue Src   = Op.getOperand(2);
16042     SDValue Base  = Op.getOperand(3);
16043     SDValue Index = Op.getOperand(4);
16044     SDValue Mask  = Op.getOperand(5);
16045     SDValue Scale = Op.getOperand(6);
16046     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16047                          Chain, Subtarget);
16048   }
16049   case SCATTER: {
16050   //scatter(base, mask, index, v1, scale);
16051     SDValue Chain = Op.getOperand(0);
16052     SDValue Base  = Op.getOperand(2);
16053     SDValue Mask  = Op.getOperand(3);
16054     SDValue Index = Op.getOperand(4);
16055     SDValue Src   = Op.getOperand(5);
16056     SDValue Scale = Op.getOperand(6);
16057     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16058                           Scale, Chain);
16059   }
16060   case PREFETCH: {
16061     SDValue Hint = Op.getOperand(6);
16062     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16063     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16064     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16065     SDValue Chain = Op.getOperand(0);
16066     SDValue Mask  = Op.getOperand(2);
16067     SDValue Index = Op.getOperand(3);
16068     SDValue Base  = Op.getOperand(4);
16069     SDValue Scale = Op.getOperand(5);
16070     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16071   }
16072   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16073   case RDTSC: {
16074     SmallVector<SDValue, 2> Results;
16075     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16076                             Results);
16077     return DAG.getMergeValues(Results, dl);
16078   }
16079   // Read Performance Monitoring Counters.
16080   case RDPMC: {
16081     SmallVector<SDValue, 2> Results;
16082     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16083     return DAG.getMergeValues(Results, dl);
16084   }
16085   // XTEST intrinsics.
16086   case XTEST: {
16087     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16088     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16089     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16090                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16091                                 InTrans);
16092     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16093     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16094                        Ret, SDValue(InTrans.getNode(), 1));
16095   }
16096   // ADC/ADCX/SBB
16097   case ADX: {
16098     SmallVector<SDValue, 2> Results;
16099     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16100     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16101     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16102                                 DAG.getConstant(-1, dl, MVT::i8));
16103     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16104                               Op.getOperand(4), GenCF.getValue(1));
16105     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16106                                  Op.getOperand(5), MachinePointerInfo(),
16107                                  false, false, 0);
16108     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16109                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16110                                 Res.getValue(1));
16111     Results.push_back(SetCC);
16112     Results.push_back(Store);
16113     return DAG.getMergeValues(Results, dl);
16114   }
16115   case COMPRESS_TO_MEM: {
16116     SDLoc dl(Op);
16117     SDValue Mask = Op.getOperand(4);
16118     SDValue DataToCompress = Op.getOperand(3);
16119     SDValue Addr = Op.getOperand(2);
16120     SDValue Chain = Op.getOperand(0);
16121
16122     EVT VT = DataToCompress.getValueType();
16123     if (isAllOnes(Mask)) // return just a store
16124       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16125                           MachinePointerInfo(), false, false,
16126                           VT.getScalarSizeInBits()/8);
16127
16128     SDValue Compressed =
16129       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16130                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16131     return DAG.getStore(Chain, dl, Compressed, Addr,
16132                         MachinePointerInfo(), false, false,
16133                         VT.getScalarSizeInBits()/8);
16134   }
16135   case EXPAND_FROM_MEM: {
16136     SDLoc dl(Op);
16137     SDValue Mask = Op.getOperand(4);
16138     SDValue PassThru = Op.getOperand(3);
16139     SDValue Addr = Op.getOperand(2);
16140     SDValue Chain = Op.getOperand(0);
16141     EVT VT = Op.getValueType();
16142
16143     if (isAllOnes(Mask)) // return just a load
16144       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16145                          false, VT.getScalarSizeInBits()/8);
16146
16147     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16148                                        false, false, false,
16149                                        VT.getScalarSizeInBits()/8);
16150
16151     SDValue Results[] = {
16152       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16153                            Mask, PassThru, Subtarget, DAG), Chain};
16154     return DAG.getMergeValues(Results, dl);
16155   }
16156   }
16157 }
16158
16159 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16160                                            SelectionDAG &DAG) const {
16161   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16162   MFI->setReturnAddressIsTaken(true);
16163
16164   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16165     return SDValue();
16166
16167   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16168   SDLoc dl(Op);
16169   EVT PtrVT = getPointerTy();
16170
16171   if (Depth > 0) {
16172     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16173     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16174     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16175     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16176                        DAG.getNode(ISD::ADD, dl, PtrVT,
16177                                    FrameAddr, Offset),
16178                        MachinePointerInfo(), false, false, false, 0);
16179   }
16180
16181   // Just load the return address.
16182   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16183   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16184                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16185 }
16186
16187 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16188   MachineFunction &MF = DAG.getMachineFunction();
16189   MachineFrameInfo *MFI = MF.getFrameInfo();
16190   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16191   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16192   EVT VT = Op.getValueType();
16193
16194   MFI->setFrameAddressIsTaken(true);
16195
16196   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16197     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16198     // is not possible to crawl up the stack without looking at the unwind codes
16199     // simultaneously.
16200     int FrameAddrIndex = FuncInfo->getFAIndex();
16201     if (!FrameAddrIndex) {
16202       // Set up a frame object for the return address.
16203       unsigned SlotSize = RegInfo->getSlotSize();
16204       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16205           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16206       FuncInfo->setFAIndex(FrameAddrIndex);
16207     }
16208     return DAG.getFrameIndex(FrameAddrIndex, VT);
16209   }
16210
16211   unsigned FrameReg =
16212       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16213   SDLoc dl(Op);  // FIXME probably not meaningful
16214   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16215   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16216           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16217          "Invalid Frame Register!");
16218   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16219   while (Depth--)
16220     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16221                             MachinePointerInfo(),
16222                             false, false, false, 0);
16223   return FrameAddr;
16224 }
16225
16226 // FIXME? Maybe this could be a TableGen attribute on some registers and
16227 // this table could be generated automatically from RegInfo.
16228 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
16229                                               EVT VT) const {
16230   unsigned Reg = StringSwitch<unsigned>(RegName)
16231                        .Case("esp", X86::ESP)
16232                        .Case("rsp", X86::RSP)
16233                        .Default(0);
16234   if (Reg)
16235     return Reg;
16236   report_fatal_error("Invalid register name global variable");
16237 }
16238
16239 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16240                                                      SelectionDAG &DAG) const {
16241   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16242   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16243 }
16244
16245 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16246   SDValue Chain     = Op.getOperand(0);
16247   SDValue Offset    = Op.getOperand(1);
16248   SDValue Handler   = Op.getOperand(2);
16249   SDLoc dl      (Op);
16250
16251   EVT PtrVT = getPointerTy();
16252   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16253   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16254   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16255           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16256          "Invalid Frame Register!");
16257   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16258   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16259
16260   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16261                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16262                                                        dl));
16263   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16264   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16265                        false, false, 0);
16266   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16267
16268   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16269                      DAG.getRegister(StoreAddrReg, PtrVT));
16270 }
16271
16272 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16273                                                SelectionDAG &DAG) const {
16274   SDLoc DL(Op);
16275   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16276                      DAG.getVTList(MVT::i32, MVT::Other),
16277                      Op.getOperand(0), Op.getOperand(1));
16278 }
16279
16280 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16281                                                 SelectionDAG &DAG) const {
16282   SDLoc DL(Op);
16283   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16284                      Op.getOperand(0), Op.getOperand(1));
16285 }
16286
16287 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16288   return Op.getOperand(0);
16289 }
16290
16291 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16292                                                 SelectionDAG &DAG) const {
16293   SDValue Root = Op.getOperand(0);
16294   SDValue Trmp = Op.getOperand(1); // trampoline
16295   SDValue FPtr = Op.getOperand(2); // nested function
16296   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16297   SDLoc dl (Op);
16298
16299   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16300   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16301
16302   if (Subtarget->is64Bit()) {
16303     SDValue OutChains[6];
16304
16305     // Large code-model.
16306     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16307     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16308
16309     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16310     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16311
16312     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16313
16314     // Load the pointer to the nested function into R11.
16315     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16316     SDValue Addr = Trmp;
16317     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16318                                 Addr, MachinePointerInfo(TrmpAddr),
16319                                 false, false, 0);
16320
16321     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16322                        DAG.getConstant(2, dl, MVT::i64));
16323     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16324                                 MachinePointerInfo(TrmpAddr, 2),
16325                                 false, false, 2);
16326
16327     // Load the 'nest' parameter value into R10.
16328     // R10 is specified in X86CallingConv.td
16329     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16330     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16331                        DAG.getConstant(10, dl, MVT::i64));
16332     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16333                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16334                                 false, false, 0);
16335
16336     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16337                        DAG.getConstant(12, dl, MVT::i64));
16338     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16339                                 MachinePointerInfo(TrmpAddr, 12),
16340                                 false, false, 2);
16341
16342     // Jump to the nested function.
16343     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16344     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16345                        DAG.getConstant(20, dl, MVT::i64));
16346     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16347                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16348                                 false, false, 0);
16349
16350     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16351     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16352                        DAG.getConstant(22, dl, MVT::i64));
16353     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16354                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16355                                 false, false, 0);
16356
16357     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16358   } else {
16359     const Function *Func =
16360       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16361     CallingConv::ID CC = Func->getCallingConv();
16362     unsigned NestReg;
16363
16364     switch (CC) {
16365     default:
16366       llvm_unreachable("Unsupported calling convention");
16367     case CallingConv::C:
16368     case CallingConv::X86_StdCall: {
16369       // Pass 'nest' parameter in ECX.
16370       // Must be kept in sync with X86CallingConv.td
16371       NestReg = X86::ECX;
16372
16373       // Check that ECX wasn't needed by an 'inreg' parameter.
16374       FunctionType *FTy = Func->getFunctionType();
16375       const AttributeSet &Attrs = Func->getAttributes();
16376
16377       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16378         unsigned InRegCount = 0;
16379         unsigned Idx = 1;
16380
16381         for (FunctionType::param_iterator I = FTy->param_begin(),
16382              E = FTy->param_end(); I != E; ++I, ++Idx)
16383           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16384             // FIXME: should only count parameters that are lowered to integers.
16385             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16386
16387         if (InRegCount > 2) {
16388           report_fatal_error("Nest register in use - reduce number of inreg"
16389                              " parameters!");
16390         }
16391       }
16392       break;
16393     }
16394     case CallingConv::X86_FastCall:
16395     case CallingConv::X86_ThisCall:
16396     case CallingConv::Fast:
16397       // Pass 'nest' parameter in EAX.
16398       // Must be kept in sync with X86CallingConv.td
16399       NestReg = X86::EAX;
16400       break;
16401     }
16402
16403     SDValue OutChains[4];
16404     SDValue Addr, Disp;
16405
16406     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16407                        DAG.getConstant(10, dl, MVT::i32));
16408     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16409
16410     // This is storing the opcode for MOV32ri.
16411     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16412     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16413     OutChains[0] = DAG.getStore(Root, dl,
16414                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16415                                 Trmp, MachinePointerInfo(TrmpAddr),
16416                                 false, false, 0);
16417
16418     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16419                        DAG.getConstant(1, dl, MVT::i32));
16420     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16421                                 MachinePointerInfo(TrmpAddr, 1),
16422                                 false, false, 1);
16423
16424     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16425     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16426                        DAG.getConstant(5, dl, MVT::i32));
16427     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16428                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16429                                 false, false, 1);
16430
16431     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16432                        DAG.getConstant(6, dl, MVT::i32));
16433     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16434                                 MachinePointerInfo(TrmpAddr, 6),
16435                                 false, false, 1);
16436
16437     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16438   }
16439 }
16440
16441 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16442                                             SelectionDAG &DAG) const {
16443   /*
16444    The rounding mode is in bits 11:10 of FPSR, and has the following
16445    settings:
16446      00 Round to nearest
16447      01 Round to -inf
16448      10 Round to +inf
16449      11 Round to 0
16450
16451   FLT_ROUNDS, on the other hand, expects the following:
16452     -1 Undefined
16453      0 Round to 0
16454      1 Round to nearest
16455      2 Round to +inf
16456      3 Round to -inf
16457
16458   To perform the conversion, we do:
16459     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16460   */
16461
16462   MachineFunction &MF = DAG.getMachineFunction();
16463   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16464   unsigned StackAlignment = TFI.getStackAlignment();
16465   MVT VT = Op.getSimpleValueType();
16466   SDLoc DL(Op);
16467
16468   // Save FP Control Word to stack slot
16469   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16470   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16471
16472   MachineMemOperand *MMO =
16473    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16474                            MachineMemOperand::MOStore, 2, 2);
16475
16476   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16477   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16478                                           DAG.getVTList(MVT::Other),
16479                                           Ops, MVT::i16, MMO);
16480
16481   // Load FP Control Word from stack slot
16482   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16483                             MachinePointerInfo(), false, false, false, 0);
16484
16485   // Transform as necessary
16486   SDValue CWD1 =
16487     DAG.getNode(ISD::SRL, DL, MVT::i16,
16488                 DAG.getNode(ISD::AND, DL, MVT::i16,
16489                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16490                 DAG.getConstant(11, DL, MVT::i8));
16491   SDValue CWD2 =
16492     DAG.getNode(ISD::SRL, DL, MVT::i16,
16493                 DAG.getNode(ISD::AND, DL, MVT::i16,
16494                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16495                 DAG.getConstant(9, DL, MVT::i8));
16496
16497   SDValue RetVal =
16498     DAG.getNode(ISD::AND, DL, MVT::i16,
16499                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16500                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16501                             DAG.getConstant(1, DL, MVT::i16)),
16502                 DAG.getConstant(3, DL, MVT::i16));
16503
16504   return DAG.getNode((VT.getSizeInBits() < 16 ?
16505                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16506 }
16507
16508 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16509   MVT VT = Op.getSimpleValueType();
16510   EVT OpVT = VT;
16511   unsigned NumBits = VT.getSizeInBits();
16512   SDLoc dl(Op);
16513
16514   Op = Op.getOperand(0);
16515   if (VT == MVT::i8) {
16516     // Zero extend to i32 since there is not an i8 bsr.
16517     OpVT = MVT::i32;
16518     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16519   }
16520
16521   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16522   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16523   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16524
16525   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16526   SDValue Ops[] = {
16527     Op,
16528     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16529     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16530     Op.getValue(1)
16531   };
16532   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16533
16534   // Finally xor with NumBits-1.
16535   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16536                    DAG.getConstant(NumBits - 1, dl, OpVT));
16537
16538   if (VT == MVT::i8)
16539     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16540   return Op;
16541 }
16542
16543 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16544   MVT VT = Op.getSimpleValueType();
16545   EVT OpVT = VT;
16546   unsigned NumBits = VT.getSizeInBits();
16547   SDLoc dl(Op);
16548
16549   Op = Op.getOperand(0);
16550   if (VT == MVT::i8) {
16551     // Zero extend to i32 since there is not an i8 bsr.
16552     OpVT = MVT::i32;
16553     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16554   }
16555
16556   // Issue a bsr (scan bits in reverse).
16557   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16558   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16559
16560   // And xor with NumBits-1.
16561   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16562                    DAG.getConstant(NumBits - 1, dl, OpVT));
16563
16564   if (VT == MVT::i8)
16565     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16566   return Op;
16567 }
16568
16569 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16570   MVT VT = Op.getSimpleValueType();
16571   unsigned NumBits = VT.getSizeInBits();
16572   SDLoc dl(Op);
16573   Op = Op.getOperand(0);
16574
16575   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16576   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16577   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16578
16579   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16580   SDValue Ops[] = {
16581     Op,
16582     DAG.getConstant(NumBits, dl, VT),
16583     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16584     Op.getValue(1)
16585   };
16586   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16587 }
16588
16589 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16590 // ones, and then concatenate the result back.
16591 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16592   MVT VT = Op.getSimpleValueType();
16593
16594   assert(VT.is256BitVector() && VT.isInteger() &&
16595          "Unsupported value type for operation");
16596
16597   unsigned NumElems = VT.getVectorNumElements();
16598   SDLoc dl(Op);
16599
16600   // Extract the LHS vectors
16601   SDValue LHS = Op.getOperand(0);
16602   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16603   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16604
16605   // Extract the RHS vectors
16606   SDValue RHS = Op.getOperand(1);
16607   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16608   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16609
16610   MVT EltVT = VT.getVectorElementType();
16611   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16612
16613   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16614                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16615                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16616 }
16617
16618 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16619   if (Op.getValueType() == MVT::i1)
16620     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16621                        Op.getOperand(0), Op.getOperand(1));
16622   assert(Op.getSimpleValueType().is256BitVector() &&
16623          Op.getSimpleValueType().isInteger() &&
16624          "Only handle AVX 256-bit vector integer operation");
16625   return Lower256IntArith(Op, DAG);
16626 }
16627
16628 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16629   if (Op.getValueType() == MVT::i1)
16630     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16631                        Op.getOperand(0), Op.getOperand(1));
16632   assert(Op.getSimpleValueType().is256BitVector() &&
16633          Op.getSimpleValueType().isInteger() &&
16634          "Only handle AVX 256-bit vector integer operation");
16635   return Lower256IntArith(Op, DAG);
16636 }
16637
16638 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16639                         SelectionDAG &DAG) {
16640   SDLoc dl(Op);
16641   MVT VT = Op.getSimpleValueType();
16642
16643   if (VT == MVT::i1)
16644     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16645
16646   // Decompose 256-bit ops into smaller 128-bit ops.
16647   if (VT.is256BitVector() && !Subtarget->hasInt256())
16648     return Lower256IntArith(Op, DAG);
16649
16650   SDValue A = Op.getOperand(0);
16651   SDValue B = Op.getOperand(1);
16652
16653   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16654   // pairs, multiply and truncate.
16655   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16656     if (Subtarget->hasInt256()) {
16657       if (VT == MVT::v32i8) {
16658         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16659         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16660         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16661         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16662         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16663         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16664         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16665         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16666                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16667                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16668       }
16669
16670       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16671       return DAG.getNode(
16672           ISD::TRUNCATE, dl, VT,
16673           DAG.getNode(ISD::MUL, dl, ExVT,
16674                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16675                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16676     }
16677
16678     assert(VT == MVT::v16i8 &&
16679            "Pre-AVX2 support only supports v16i8 multiplication");
16680     MVT ExVT = MVT::v8i16;
16681
16682     // Extract the lo parts and sign extend to i16
16683     SDValue ALo, BLo;
16684     if (Subtarget->hasSSE41()) {
16685       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16686       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16687     } else {
16688       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16689                               -1, 4, -1, 5, -1, 6, -1, 7};
16690       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16691       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16692       ALo = DAG.getBitcast(ExVT, ALo);
16693       BLo = DAG.getBitcast(ExVT, BLo);
16694       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16695       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16696     }
16697
16698     // Extract the hi parts and sign extend to i16
16699     SDValue AHi, BHi;
16700     if (Subtarget->hasSSE41()) {
16701       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16702                               -1, -1, -1, -1, -1, -1, -1, -1};
16703       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16704       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16705       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16706       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16707     } else {
16708       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16709                               -1, 12, -1, 13, -1, 14, -1, 15};
16710       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16711       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16712       AHi = DAG.getBitcast(ExVT, AHi);
16713       BHi = DAG.getBitcast(ExVT, BHi);
16714       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16715       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16716     }
16717
16718     // Multiply, mask the lower 8bits of the lo/hi results and pack
16719     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16720     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16721     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16722     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16723     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16724   }
16725
16726   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16727   if (VT == MVT::v4i32) {
16728     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16729            "Should not custom lower when pmuldq is available!");
16730
16731     // Extract the odd parts.
16732     static const int UnpackMask[] = { 1, -1, 3, -1 };
16733     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16734     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16735
16736     // Multiply the even parts.
16737     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16738     // Now multiply odd parts.
16739     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16740
16741     Evens = DAG.getBitcast(VT, Evens);
16742     Odds = DAG.getBitcast(VT, Odds);
16743
16744     // Merge the two vectors back together with a shuffle. This expands into 2
16745     // shuffles.
16746     static const int ShufMask[] = { 0, 4, 2, 6 };
16747     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16748   }
16749
16750   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16751          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16752
16753   //  Ahi = psrlqi(a, 32);
16754   //  Bhi = psrlqi(b, 32);
16755   //
16756   //  AloBlo = pmuludq(a, b);
16757   //  AloBhi = pmuludq(a, Bhi);
16758   //  AhiBlo = pmuludq(Ahi, b);
16759
16760   //  AloBhi = psllqi(AloBhi, 32);
16761   //  AhiBlo = psllqi(AhiBlo, 32);
16762   //  return AloBlo + AloBhi + AhiBlo;
16763
16764   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16765   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16766
16767   SDValue AhiBlo = Ahi;
16768   SDValue AloBhi = Bhi;
16769   // Bit cast to 32-bit vectors for MULUDQ
16770   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16771                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16772   A = DAG.getBitcast(MulVT, A);
16773   B = DAG.getBitcast(MulVT, B);
16774   Ahi = DAG.getBitcast(MulVT, Ahi);
16775   Bhi = DAG.getBitcast(MulVT, Bhi);
16776
16777   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16778   // After shifting right const values the result may be all-zero.
16779   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16780     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16781     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16782   }
16783   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16784     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16785     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16786   }
16787
16788   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16789   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16790 }
16791
16792 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16793   assert(Subtarget->isTargetWin64() && "Unexpected target");
16794   EVT VT = Op.getValueType();
16795   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16796          "Unexpected return type for lowering");
16797
16798   RTLIB::Libcall LC;
16799   bool isSigned;
16800   switch (Op->getOpcode()) {
16801   default: llvm_unreachable("Unexpected request for libcall!");
16802   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16803   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16804   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16805   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16806   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16807   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16808   }
16809
16810   SDLoc dl(Op);
16811   SDValue InChain = DAG.getEntryNode();
16812
16813   TargetLowering::ArgListTy Args;
16814   TargetLowering::ArgListEntry Entry;
16815   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16816     EVT ArgVT = Op->getOperand(i).getValueType();
16817     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16818            "Unexpected argument type for lowering");
16819     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16820     Entry.Node = StackPtr;
16821     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16822                            false, false, 16);
16823     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16824     Entry.Ty = PointerType::get(ArgTy,0);
16825     Entry.isSExt = false;
16826     Entry.isZExt = false;
16827     Args.push_back(Entry);
16828   }
16829
16830   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16831                                          getPointerTy());
16832
16833   TargetLowering::CallLoweringInfo CLI(DAG);
16834   CLI.setDebugLoc(dl).setChain(InChain)
16835     .setCallee(getLibcallCallingConv(LC),
16836                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16837                Callee, std::move(Args), 0)
16838     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16839
16840   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16841   return DAG.getBitcast(VT, CallInfo.first);
16842 }
16843
16844 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16845                              SelectionDAG &DAG) {
16846   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16847   EVT VT = Op0.getValueType();
16848   SDLoc dl(Op);
16849
16850   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16851          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16852
16853   // PMULxD operations multiply each even value (starting at 0) of LHS with
16854   // the related value of RHS and produce a widen result.
16855   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16856   // => <2 x i64> <ae|cg>
16857   //
16858   // In other word, to have all the results, we need to perform two PMULxD:
16859   // 1. one with the even values.
16860   // 2. one with the odd values.
16861   // To achieve #2, with need to place the odd values at an even position.
16862   //
16863   // Place the odd value at an even position (basically, shift all values 1
16864   // step to the left):
16865   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16866   // <a|b|c|d> => <b|undef|d|undef>
16867   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16868   // <e|f|g|h> => <f|undef|h|undef>
16869   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16870
16871   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16872   // ints.
16873   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16874   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16875   unsigned Opcode =
16876       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16877   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16878   // => <2 x i64> <ae|cg>
16879   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16880   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16881   // => <2 x i64> <bf|dh>
16882   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16883
16884   // Shuffle it back into the right order.
16885   SDValue Highs, Lows;
16886   if (VT == MVT::v8i32) {
16887     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16888     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16889     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16890     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16891   } else {
16892     const int HighMask[] = {1, 5, 3, 7};
16893     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16894     const int LowMask[] = {0, 4, 2, 6};
16895     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16896   }
16897
16898   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16899   // unsigned multiply.
16900   if (IsSigned && !Subtarget->hasSSE41()) {
16901     SDValue ShAmt =
16902         DAG.getConstant(31, dl,
16903                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16904     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16905                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16906     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16907                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16908
16909     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16910     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16911   }
16912
16913   // The first result of MUL_LOHI is actually the low value, followed by the
16914   // high value.
16915   SDValue Ops[] = {Lows, Highs};
16916   return DAG.getMergeValues(Ops, dl);
16917 }
16918
16919 // Return true if the requred (according to Opcode) shift-imm form is natively
16920 // supported by the Subtarget
16921 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16922                                         unsigned Opcode) {
16923   if (VT.getScalarSizeInBits() < 16)
16924     return false;
16925
16926   if (VT.is512BitVector() &&
16927       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16928     return true;
16929
16930   bool LShift = VT.is128BitVector() ||
16931     (VT.is256BitVector() && Subtarget->hasInt256());
16932
16933   bool AShift = LShift && (Subtarget->hasVLX() ||
16934     (VT != MVT::v2i64 && VT != MVT::v4i64));
16935   return (Opcode == ISD::SRA) ? AShift : LShift;
16936 }
16937
16938 // The shift amount is a variable, but it is the same for all vector lanes.
16939 // These instrcutions are defined together with shift-immediate.
16940 static
16941 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
16942                                       unsigned Opcode) {
16943   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16944 }
16945
16946 // Return true if the requred (according to Opcode) variable-shift form is
16947 // natively supported by the Subtarget
16948 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
16949                                     unsigned Opcode) {
16950
16951   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16952     return false;
16953
16954   // vXi16 supported only on AVX-512, BWI
16955   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16956     return false;
16957
16958   if (VT.is512BitVector() || Subtarget->hasVLX())
16959     return true;
16960
16961   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16962   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16963   return (Opcode == ISD::SRA) ? AShift : LShift;
16964 }
16965
16966 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16967                                          const X86Subtarget *Subtarget) {
16968   MVT VT = Op.getSimpleValueType();
16969   SDLoc dl(Op);
16970   SDValue R = Op.getOperand(0);
16971   SDValue Amt = Op.getOperand(1);
16972
16973   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16974     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16975
16976   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
16977     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
16978     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
16979     SDValue Ex = DAG.getBitcast(ExVT, R);
16980
16981     if (ShiftAmt >= 32) {
16982       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
16983       SDValue Upper =
16984           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
16985       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
16986                                                  ShiftAmt - 32, DAG);
16987       if (VT == MVT::v2i64)
16988         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
16989       if (VT == MVT::v4i64)
16990         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
16991                                   {9, 1, 11, 3, 13, 5, 15, 7});
16992     } else {
16993       // SRA upper i32, SHL whole i64 and select lower i32.
16994       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
16995                                                  ShiftAmt, DAG);
16996       SDValue Lower =
16997           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
16998       Lower = DAG.getBitcast(ExVT, Lower);
16999       if (VT == MVT::v2i64)
17000         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17001       if (VT == MVT::v4i64)
17002         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17003                                   {8, 1, 10, 3, 12, 5, 14, 7});
17004     }
17005     return DAG.getBitcast(VT, Ex);
17006   };
17007
17008   // Optimize shl/srl/sra with constant shift amount.
17009   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17010     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17011       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17012
17013       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17014         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17015
17016       // i64 SRA needs to be performed as partial shifts.
17017       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17018           Op.getOpcode() == ISD::SRA)
17019         return ArithmeticShiftRight64(ShiftAmt);
17020
17021       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17022         unsigned NumElts = VT.getVectorNumElements();
17023         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17024
17025         if (Op.getOpcode() == ISD::SHL) {
17026           // Simple i8 add case
17027           if (ShiftAmt == 1)
17028             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17029
17030           // Make a large shift.
17031           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17032                                                    R, ShiftAmt, DAG);
17033           SHL = DAG.getBitcast(VT, SHL);
17034           // Zero out the rightmost bits.
17035           SmallVector<SDValue, 32> V(
17036               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17037           return DAG.getNode(ISD::AND, dl, VT, SHL,
17038                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17039         }
17040         if (Op.getOpcode() == ISD::SRL) {
17041           // Make a large shift.
17042           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17043                                                    R, ShiftAmt, DAG);
17044           SRL = DAG.getBitcast(VT, SRL);
17045           // Zero out the leftmost bits.
17046           SmallVector<SDValue, 32> V(
17047               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17048           return DAG.getNode(ISD::AND, dl, VT, SRL,
17049                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17050         }
17051         if (Op.getOpcode() == ISD::SRA) {
17052           if (ShiftAmt == 7) {
17053             // R s>> 7  ===  R s< 0
17054             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17055             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17056           }
17057
17058           // R s>> a === ((R u>> a) ^ m) - m
17059           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17060           SmallVector<SDValue, 32> V(NumElts,
17061                                      DAG.getConstant(128 >> ShiftAmt, dl,
17062                                                      MVT::i8));
17063           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17064           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17065           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17066           return Res;
17067         }
17068         llvm_unreachable("Unknown shift opcode.");
17069       }
17070     }
17071   }
17072
17073   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17074   if (!Subtarget->is64Bit() &&
17075       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17076       Amt.getOpcode() == ISD::BITCAST &&
17077       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17078     Amt = Amt.getOperand(0);
17079     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17080                      VT.getVectorNumElements();
17081     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17082     uint64_t ShiftAmt = 0;
17083     for (unsigned i = 0; i != Ratio; ++i) {
17084       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17085       if (!C)
17086         return SDValue();
17087       // 6 == Log2(64)
17088       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17089     }
17090     // Check remaining shift amounts.
17091     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17092       uint64_t ShAmt = 0;
17093       for (unsigned j = 0; j != Ratio; ++j) {
17094         ConstantSDNode *C =
17095           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17096         if (!C)
17097           return SDValue();
17098         // 6 == Log2(64)
17099         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17100       }
17101       if (ShAmt != ShiftAmt)
17102         return SDValue();
17103     }
17104
17105     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17106       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17107
17108     if (Op.getOpcode() == ISD::SRA)
17109       return ArithmeticShiftRight64(ShiftAmt);
17110   }
17111
17112   return SDValue();
17113 }
17114
17115 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17116                                         const X86Subtarget* Subtarget) {
17117   MVT VT = Op.getSimpleValueType();
17118   SDLoc dl(Op);
17119   SDValue R = Op.getOperand(0);
17120   SDValue Amt = Op.getOperand(1);
17121
17122   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17123     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17124
17125   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17126     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17127
17128   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17129     SDValue BaseShAmt;
17130     EVT EltVT = VT.getVectorElementType();
17131
17132     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17133       // Check if this build_vector node is doing a splat.
17134       // If so, then set BaseShAmt equal to the splat value.
17135       BaseShAmt = BV->getSplatValue();
17136       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17137         BaseShAmt = SDValue();
17138     } else {
17139       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17140         Amt = Amt.getOperand(0);
17141
17142       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17143       if (SVN && SVN->isSplat()) {
17144         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17145         SDValue InVec = Amt.getOperand(0);
17146         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17147           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17148                  "Unexpected shuffle index found!");
17149           BaseShAmt = InVec.getOperand(SplatIdx);
17150         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17151            if (ConstantSDNode *C =
17152                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17153              if (C->getZExtValue() == SplatIdx)
17154                BaseShAmt = InVec.getOperand(1);
17155            }
17156         }
17157
17158         if (!BaseShAmt)
17159           // Avoid introducing an extract element from a shuffle.
17160           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17161                                   DAG.getIntPtrConstant(SplatIdx, dl));
17162       }
17163     }
17164
17165     if (BaseShAmt.getNode()) {
17166       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17167       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17168         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17169       else if (EltVT.bitsLT(MVT::i32))
17170         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17171
17172       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17173     }
17174   }
17175
17176   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17177   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17178       Amt.getOpcode() == ISD::BITCAST &&
17179       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17180     Amt = Amt.getOperand(0);
17181     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17182                      VT.getVectorNumElements();
17183     std::vector<SDValue> Vals(Ratio);
17184     for (unsigned i = 0; i != Ratio; ++i)
17185       Vals[i] = Amt.getOperand(i);
17186     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17187       for (unsigned j = 0; j != Ratio; ++j)
17188         if (Vals[j] != Amt.getOperand(i + j))
17189           return SDValue();
17190     }
17191
17192     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17193       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17194   }
17195   return SDValue();
17196 }
17197
17198 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17199                           SelectionDAG &DAG) {
17200   MVT VT = Op.getSimpleValueType();
17201   SDLoc dl(Op);
17202   SDValue R = Op.getOperand(0);
17203   SDValue Amt = Op.getOperand(1);
17204
17205   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17206   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17207
17208   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17209     return V;
17210
17211   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17212       return V;
17213
17214   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17215     return Op;
17216
17217   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17218   // shifts per-lane and then shuffle the partial results back together.
17219   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17220     // Splat the shift amounts so the scalar shifts above will catch it.
17221     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17222     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17223     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17224     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17225     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17226   }
17227
17228   // If possible, lower this packed shift into a vector multiply instead of
17229   // expanding it into a sequence of scalar shifts.
17230   // Do this only if the vector shift count is a constant build_vector.
17231   if (Op.getOpcode() == ISD::SHL &&
17232       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17233        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17234       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17235     SmallVector<SDValue, 8> Elts;
17236     EVT SVT = VT.getScalarType();
17237     unsigned SVTBits = SVT.getSizeInBits();
17238     const APInt &One = APInt(SVTBits, 1);
17239     unsigned NumElems = VT.getVectorNumElements();
17240
17241     for (unsigned i=0; i !=NumElems; ++i) {
17242       SDValue Op = Amt->getOperand(i);
17243       if (Op->getOpcode() == ISD::UNDEF) {
17244         Elts.push_back(Op);
17245         continue;
17246       }
17247
17248       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17249       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17250       uint64_t ShAmt = C.getZExtValue();
17251       if (ShAmt >= SVTBits) {
17252         Elts.push_back(DAG.getUNDEF(SVT));
17253         continue;
17254       }
17255       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17256     }
17257     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17258     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17259   }
17260
17261   // Lower SHL with variable shift amount.
17262   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17263     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17264
17265     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17266                      DAG.getConstant(0x3f800000U, dl, VT));
17267     Op = DAG.getBitcast(MVT::v4f32, Op);
17268     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17269     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17270   }
17271
17272   // If possible, lower this shift as a sequence of two shifts by
17273   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17274   // Example:
17275   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17276   //
17277   // Could be rewritten as:
17278   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17279   //
17280   // The advantage is that the two shifts from the example would be
17281   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17282   // the vector shift into four scalar shifts plus four pairs of vector
17283   // insert/extract.
17284   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17285       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17286     unsigned TargetOpcode = X86ISD::MOVSS;
17287     bool CanBeSimplified;
17288     // The splat value for the first packed shift (the 'X' from the example).
17289     SDValue Amt1 = Amt->getOperand(0);
17290     // The splat value for the second packed shift (the 'Y' from the example).
17291     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17292                                         Amt->getOperand(2);
17293
17294     // See if it is possible to replace this node with a sequence of
17295     // two shifts followed by a MOVSS/MOVSD
17296     if (VT == MVT::v4i32) {
17297       // Check if it is legal to use a MOVSS.
17298       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17299                         Amt2 == Amt->getOperand(3);
17300       if (!CanBeSimplified) {
17301         // Otherwise, check if we can still simplify this node using a MOVSD.
17302         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17303                           Amt->getOperand(2) == Amt->getOperand(3);
17304         TargetOpcode = X86ISD::MOVSD;
17305         Amt2 = Amt->getOperand(2);
17306       }
17307     } else {
17308       // Do similar checks for the case where the machine value type
17309       // is MVT::v8i16.
17310       CanBeSimplified = Amt1 == Amt->getOperand(1);
17311       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17312         CanBeSimplified = Amt2 == Amt->getOperand(i);
17313
17314       if (!CanBeSimplified) {
17315         TargetOpcode = X86ISD::MOVSD;
17316         CanBeSimplified = true;
17317         Amt2 = Amt->getOperand(4);
17318         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17319           CanBeSimplified = Amt1 == Amt->getOperand(i);
17320         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17321           CanBeSimplified = Amt2 == Amt->getOperand(j);
17322       }
17323     }
17324
17325     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17326         isa<ConstantSDNode>(Amt2)) {
17327       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17328       EVT CastVT = MVT::v4i32;
17329       SDValue Splat1 =
17330         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17331       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17332       SDValue Splat2 =
17333         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17334       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17335       if (TargetOpcode == X86ISD::MOVSD)
17336         CastVT = MVT::v2i64;
17337       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17338       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17339       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17340                                             BitCast1, DAG);
17341       return DAG.getBitcast(VT, Result);
17342     }
17343   }
17344
17345   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17346     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17347     unsigned ShiftOpcode = Op->getOpcode();
17348
17349     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17350       // On SSE41 targets we make use of the fact that VSELECT lowers
17351       // to PBLENDVB which selects bytes based just on the sign bit.
17352       if (Subtarget->hasSSE41()) {
17353         V0 = DAG.getBitcast(VT, V0);
17354         V1 = DAG.getBitcast(VT, V1);
17355         Sel = DAG.getBitcast(VT, Sel);
17356         return DAG.getBitcast(SelVT,
17357                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17358       }
17359       // On pre-SSE41 targets we test for the sign bit by comparing to
17360       // zero - a negative value will set all bits of the lanes to true
17361       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17362       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17363       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17364       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17365     };
17366
17367     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17368     // We can safely do this using i16 shifts as we're only interested in
17369     // the 3 lower bits of each byte.
17370     Amt = DAG.getBitcast(ExtVT, Amt);
17371     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17372     Amt = DAG.getBitcast(VT, Amt);
17373
17374     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17375       // r = VSELECT(r, shift(r, 4), a);
17376       SDValue M =
17377           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17378       R = SignBitSelect(VT, Amt, M, R);
17379
17380       // a += a
17381       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17382
17383       // r = VSELECT(r, shift(r, 2), a);
17384       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17385       R = SignBitSelect(VT, Amt, M, R);
17386
17387       // a += a
17388       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17389
17390       // return VSELECT(r, shift(r, 1), a);
17391       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17392       R = SignBitSelect(VT, Amt, M, R);
17393       return R;
17394     }
17395
17396     if (Op->getOpcode() == ISD::SRA) {
17397       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17398       // so we can correctly sign extend. We don't care what happens to the
17399       // lower byte.
17400       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17401       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17402       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17403       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17404       ALo = DAG.getBitcast(ExtVT, ALo);
17405       AHi = DAG.getBitcast(ExtVT, AHi);
17406       RLo = DAG.getBitcast(ExtVT, RLo);
17407       RHi = DAG.getBitcast(ExtVT, RHi);
17408
17409       // r = VSELECT(r, shift(r, 4), a);
17410       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17411                                 DAG.getConstant(4, dl, ExtVT));
17412       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17413                                 DAG.getConstant(4, dl, ExtVT));
17414       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17415       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17416
17417       // a += a
17418       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17419       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17420
17421       // r = VSELECT(r, shift(r, 2), a);
17422       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17423                         DAG.getConstant(2, dl, ExtVT));
17424       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17425                         DAG.getConstant(2, dl, ExtVT));
17426       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17427       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17428
17429       // a += a
17430       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17431       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17432
17433       // r = VSELECT(r, shift(r, 1), a);
17434       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17435                         DAG.getConstant(1, dl, ExtVT));
17436       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17437                         DAG.getConstant(1, dl, ExtVT));
17438       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17439       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17440
17441       // Logical shift the result back to the lower byte, leaving a zero upper
17442       // byte
17443       // meaning that we can safely pack with PACKUSWB.
17444       RLo =
17445           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17446       RHi =
17447           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17448       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17449     }
17450   }
17451
17452   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17453   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17454   // solution better.
17455   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17456     MVT ExtVT = MVT::v8i32;
17457     unsigned ExtOpc =
17458         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17459     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17460     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17461     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17462                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17463   }
17464
17465   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17466     MVT ExtVT = MVT::v8i32;
17467     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17468     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17469     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17470     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17471     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17472     ALo = DAG.getBitcast(ExtVT, ALo);
17473     AHi = DAG.getBitcast(ExtVT, AHi);
17474     RLo = DAG.getBitcast(ExtVT, RLo);
17475     RHi = DAG.getBitcast(ExtVT, RHi);
17476     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17477     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17478     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17479     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17480     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17481   }
17482
17483   if (VT == MVT::v8i16) {
17484     unsigned ShiftOpcode = Op->getOpcode();
17485
17486     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17487       // On SSE41 targets we make use of the fact that VSELECT lowers
17488       // to PBLENDVB which selects bytes based just on the sign bit.
17489       if (Subtarget->hasSSE41()) {
17490         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17491         V0 = DAG.getBitcast(ExtVT, V0);
17492         V1 = DAG.getBitcast(ExtVT, V1);
17493         Sel = DAG.getBitcast(ExtVT, Sel);
17494         return DAG.getBitcast(
17495             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17496       }
17497       // On pre-SSE41 targets we splat the sign bit - a negative value will
17498       // set all bits of the lanes to true and VSELECT uses that in
17499       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17500       SDValue C =
17501           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17502       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17503     };
17504
17505     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17506     if (Subtarget->hasSSE41()) {
17507       // On SSE41 targets we need to replicate the shift mask in both
17508       // bytes for PBLENDVB.
17509       Amt = DAG.getNode(
17510           ISD::OR, dl, VT,
17511           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17512           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17513     } else {
17514       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17515     }
17516
17517     // r = VSELECT(r, shift(r, 8), a);
17518     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17519     R = SignBitSelect(Amt, M, R);
17520
17521     // a += a
17522     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17523
17524     // r = VSELECT(r, shift(r, 4), a);
17525     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17526     R = SignBitSelect(Amt, M, R);
17527
17528     // a += a
17529     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17530
17531     // r = VSELECT(r, shift(r, 2), a);
17532     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17533     R = SignBitSelect(Amt, M, R);
17534
17535     // a += a
17536     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17537
17538     // return VSELECT(r, shift(r, 1), a);
17539     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17540     R = SignBitSelect(Amt, M, R);
17541     return R;
17542   }
17543
17544   // Decompose 256-bit shifts into smaller 128-bit shifts.
17545   if (VT.is256BitVector()) {
17546     unsigned NumElems = VT.getVectorNumElements();
17547     MVT EltVT = VT.getVectorElementType();
17548     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17549
17550     // Extract the two vectors
17551     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17552     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17553
17554     // Recreate the shift amount vectors
17555     SDValue Amt1, Amt2;
17556     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17557       // Constant shift amount
17558       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17559       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17560       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17561
17562       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17563       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17564     } else {
17565       // Variable shift amount
17566       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17567       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17568     }
17569
17570     // Issue new vector shifts for the smaller types
17571     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17572     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17573
17574     // Concatenate the result back
17575     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17576   }
17577
17578   return SDValue();
17579 }
17580
17581 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17582   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17583   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17584   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17585   // has only one use.
17586   SDNode *N = Op.getNode();
17587   SDValue LHS = N->getOperand(0);
17588   SDValue RHS = N->getOperand(1);
17589   unsigned BaseOp = 0;
17590   unsigned Cond = 0;
17591   SDLoc DL(Op);
17592   switch (Op.getOpcode()) {
17593   default: llvm_unreachable("Unknown ovf instruction!");
17594   case ISD::SADDO:
17595     // A subtract of one will be selected as a INC. Note that INC doesn't
17596     // set CF, so we can't do this for UADDO.
17597     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17598       if (C->isOne()) {
17599         BaseOp = X86ISD::INC;
17600         Cond = X86::COND_O;
17601         break;
17602       }
17603     BaseOp = X86ISD::ADD;
17604     Cond = X86::COND_O;
17605     break;
17606   case ISD::UADDO:
17607     BaseOp = X86ISD::ADD;
17608     Cond = X86::COND_B;
17609     break;
17610   case ISD::SSUBO:
17611     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17612     // set CF, so we can't do this for USUBO.
17613     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17614       if (C->isOne()) {
17615         BaseOp = X86ISD::DEC;
17616         Cond = X86::COND_O;
17617         break;
17618       }
17619     BaseOp = X86ISD::SUB;
17620     Cond = X86::COND_O;
17621     break;
17622   case ISD::USUBO:
17623     BaseOp = X86ISD::SUB;
17624     Cond = X86::COND_B;
17625     break;
17626   case ISD::SMULO:
17627     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17628     Cond = X86::COND_O;
17629     break;
17630   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17631     if (N->getValueType(0) == MVT::i8) {
17632       BaseOp = X86ISD::UMUL8;
17633       Cond = X86::COND_O;
17634       break;
17635     }
17636     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17637                                  MVT::i32);
17638     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17639
17640     SDValue SetCC =
17641       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17642                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17643                   SDValue(Sum.getNode(), 2));
17644
17645     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17646   }
17647   }
17648
17649   // Also sets EFLAGS.
17650   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17651   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17652
17653   SDValue SetCC =
17654     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17655                 DAG.getConstant(Cond, DL, MVT::i32),
17656                 SDValue(Sum.getNode(), 1));
17657
17658   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17659 }
17660
17661 /// Returns true if the operand type is exactly twice the native width, and
17662 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17663 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17664 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17665 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17666   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17667
17668   if (OpWidth == 64)
17669     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17670   else if (OpWidth == 128)
17671     return Subtarget->hasCmpxchg16b();
17672   else
17673     return false;
17674 }
17675
17676 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17677   return needsCmpXchgNb(SI->getValueOperand()->getType());
17678 }
17679
17680 // Note: this turns large loads into lock cmpxchg8b/16b.
17681 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17682 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17683   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17684   return needsCmpXchgNb(PTy->getElementType());
17685 }
17686
17687 TargetLoweringBase::AtomicRMWExpansionKind
17688 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17689   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17690   const Type *MemType = AI->getType();
17691
17692   // If the operand is too big, we must see if cmpxchg8/16b is available
17693   // and default to library calls otherwise.
17694   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17695     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17696                                    : AtomicRMWExpansionKind::None;
17697   }
17698
17699   AtomicRMWInst::BinOp Op = AI->getOperation();
17700   switch (Op) {
17701   default:
17702     llvm_unreachable("Unknown atomic operation");
17703   case AtomicRMWInst::Xchg:
17704   case AtomicRMWInst::Add:
17705   case AtomicRMWInst::Sub:
17706     // It's better to use xadd, xsub or xchg for these in all cases.
17707     return AtomicRMWExpansionKind::None;
17708   case AtomicRMWInst::Or:
17709   case AtomicRMWInst::And:
17710   case AtomicRMWInst::Xor:
17711     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17712     // prefix to a normal instruction for these operations.
17713     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17714                             : AtomicRMWExpansionKind::None;
17715   case AtomicRMWInst::Nand:
17716   case AtomicRMWInst::Max:
17717   case AtomicRMWInst::Min:
17718   case AtomicRMWInst::UMax:
17719   case AtomicRMWInst::UMin:
17720     // These always require a non-trivial set of data operations on x86. We must
17721     // use a cmpxchg loop.
17722     return AtomicRMWExpansionKind::CmpXChg;
17723   }
17724 }
17725
17726 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17727   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17728   // no-sse2). There isn't any reason to disable it if the target processor
17729   // supports it.
17730   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17731 }
17732
17733 LoadInst *
17734 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17735   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17736   const Type *MemType = AI->getType();
17737   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17738   // there is no benefit in turning such RMWs into loads, and it is actually
17739   // harmful as it introduces a mfence.
17740   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17741     return nullptr;
17742
17743   auto Builder = IRBuilder<>(AI);
17744   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17745   auto SynchScope = AI->getSynchScope();
17746   // We must restrict the ordering to avoid generating loads with Release or
17747   // ReleaseAcquire orderings.
17748   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17749   auto Ptr = AI->getPointerOperand();
17750
17751   // Before the load we need a fence. Here is an example lifted from
17752   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17753   // is required:
17754   // Thread 0:
17755   //   x.store(1, relaxed);
17756   //   r1 = y.fetch_add(0, release);
17757   // Thread 1:
17758   //   y.fetch_add(42, acquire);
17759   //   r2 = x.load(relaxed);
17760   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17761   // lowered to just a load without a fence. A mfence flushes the store buffer,
17762   // making the optimization clearly correct.
17763   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17764   // otherwise, we might be able to be more agressive on relaxed idempotent
17765   // rmw. In practice, they do not look useful, so we don't try to be
17766   // especially clever.
17767   if (SynchScope == SingleThread)
17768     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17769     // the IR level, so we must wrap it in an intrinsic.
17770     return nullptr;
17771
17772   if (!hasMFENCE(*Subtarget))
17773     // FIXME: it might make sense to use a locked operation here but on a
17774     // different cache-line to prevent cache-line bouncing. In practice it
17775     // is probably a small win, and x86 processors without mfence are rare
17776     // enough that we do not bother.
17777     return nullptr;
17778
17779   Function *MFence =
17780       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17781   Builder.CreateCall(MFence, {});
17782
17783   // Finally we can emit the atomic load.
17784   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17785           AI->getType()->getPrimitiveSizeInBits());
17786   Loaded->setAtomic(Order, SynchScope);
17787   AI->replaceAllUsesWith(Loaded);
17788   AI->eraseFromParent();
17789   return Loaded;
17790 }
17791
17792 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17793                                  SelectionDAG &DAG) {
17794   SDLoc dl(Op);
17795   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17796     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17797   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17798     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17799
17800   // The only fence that needs an instruction is a sequentially-consistent
17801   // cross-thread fence.
17802   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17803     if (hasMFENCE(*Subtarget))
17804       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17805
17806     SDValue Chain = Op.getOperand(0);
17807     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17808     SDValue Ops[] = {
17809       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17810       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17811       DAG.getRegister(0, MVT::i32),            // Index
17812       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17813       DAG.getRegister(0, MVT::i32),            // Segment.
17814       Zero,
17815       Chain
17816     };
17817     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17818     return SDValue(Res, 0);
17819   }
17820
17821   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17822   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17823 }
17824
17825 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17826                              SelectionDAG &DAG) {
17827   MVT T = Op.getSimpleValueType();
17828   SDLoc DL(Op);
17829   unsigned Reg = 0;
17830   unsigned size = 0;
17831   switch(T.SimpleTy) {
17832   default: llvm_unreachable("Invalid value type!");
17833   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17834   case MVT::i16: Reg = X86::AX;  size = 2; break;
17835   case MVT::i32: Reg = X86::EAX; size = 4; break;
17836   case MVT::i64:
17837     assert(Subtarget->is64Bit() && "Node not type legal!");
17838     Reg = X86::RAX; size = 8;
17839     break;
17840   }
17841   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17842                                   Op.getOperand(2), SDValue());
17843   SDValue Ops[] = { cpIn.getValue(0),
17844                     Op.getOperand(1),
17845                     Op.getOperand(3),
17846                     DAG.getTargetConstant(size, DL, MVT::i8),
17847                     cpIn.getValue(1) };
17848   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17849   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17850   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17851                                            Ops, T, MMO);
17852
17853   SDValue cpOut =
17854     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17855   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17856                                       MVT::i32, cpOut.getValue(2));
17857   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17858                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17859                                 EFLAGS);
17860
17861   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17862   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17863   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17864   return SDValue();
17865 }
17866
17867 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17868                             SelectionDAG &DAG) {
17869   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17870   MVT DstVT = Op.getSimpleValueType();
17871
17872   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17873     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17874     if (DstVT != MVT::f64)
17875       // This conversion needs to be expanded.
17876       return SDValue();
17877
17878     SDValue InVec = Op->getOperand(0);
17879     SDLoc dl(Op);
17880     unsigned NumElts = SrcVT.getVectorNumElements();
17881     EVT SVT = SrcVT.getVectorElementType();
17882
17883     // Widen the vector in input in the case of MVT::v2i32.
17884     // Example: from MVT::v2i32 to MVT::v4i32.
17885     SmallVector<SDValue, 16> Elts;
17886     for (unsigned i = 0, e = NumElts; i != e; ++i)
17887       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17888                                  DAG.getIntPtrConstant(i, dl)));
17889
17890     // Explicitly mark the extra elements as Undef.
17891     Elts.append(NumElts, DAG.getUNDEF(SVT));
17892
17893     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17894     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17895     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
17896     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17897                        DAG.getIntPtrConstant(0, dl));
17898   }
17899
17900   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17901          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17902   assert((DstVT == MVT::i64 ||
17903           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17904          "Unexpected custom BITCAST");
17905   // i64 <=> MMX conversions are Legal.
17906   if (SrcVT==MVT::i64 && DstVT.isVector())
17907     return Op;
17908   if (DstVT==MVT::i64 && SrcVT.isVector())
17909     return Op;
17910   // MMX <=> MMX conversions are Legal.
17911   if (SrcVT.isVector() && DstVT.isVector())
17912     return Op;
17913   // All other conversions need to be expanded.
17914   return SDValue();
17915 }
17916
17917 /// Compute the horizontal sum of bytes in V for the elements of VT.
17918 ///
17919 /// Requires V to be a byte vector and VT to be an integer vector type with
17920 /// wider elements than V's type. The width of the elements of VT determines
17921 /// how many bytes of V are summed horizontally to produce each element of the
17922 /// result.
17923 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
17924                                       const X86Subtarget *Subtarget,
17925                                       SelectionDAG &DAG) {
17926   SDLoc DL(V);
17927   MVT ByteVecVT = V.getSimpleValueType();
17928   MVT EltVT = VT.getVectorElementType();
17929   int NumElts = VT.getVectorNumElements();
17930   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
17931          "Expected value to have byte element type.");
17932   assert(EltVT != MVT::i8 &&
17933          "Horizontal byte sum only makes sense for wider elements!");
17934   unsigned VecSize = VT.getSizeInBits();
17935   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
17936
17937   // PSADBW instruction horizontally add all bytes and leave the result in i64
17938   // chunks, thus directly computes the pop count for v2i64 and v4i64.
17939   if (EltVT == MVT::i64) {
17940     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17941     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
17942     return DAG.getBitcast(VT, V);
17943   }
17944
17945   if (EltVT == MVT::i32) {
17946     // We unpack the low half and high half into i32s interleaved with zeros so
17947     // that we can use PSADBW to horizontally sum them. The most useful part of
17948     // this is that it lines up the results of two PSADBW instructions to be
17949     // two v2i64 vectors which concatenated are the 4 population counts. We can
17950     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
17951     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
17952     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
17953     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
17954
17955     // Do the horizontal sums into two v2i64s.
17956     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17957     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17958                       DAG.getBitcast(ByteVecVT, Low), Zeros);
17959     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17960                        DAG.getBitcast(ByteVecVT, High), Zeros);
17961
17962     // Merge them together.
17963     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
17964     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
17965                     DAG.getBitcast(ShortVecVT, Low),
17966                     DAG.getBitcast(ShortVecVT, High));
17967
17968     return DAG.getBitcast(VT, V);
17969   }
17970
17971   // The only element type left is i16.
17972   assert(EltVT == MVT::i16 && "Unknown how to handle type");
17973
17974   // To obtain pop count for each i16 element starting from the pop count for
17975   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
17976   // right by 8. It is important to shift as i16s as i8 vector shift isn't
17977   // directly supported.
17978   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
17979   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
17980   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
17981   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
17982                   DAG.getBitcast(ByteVecVT, V));
17983   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
17984 }
17985
17986 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
17987                                         const X86Subtarget *Subtarget,
17988                                         SelectionDAG &DAG) {
17989   MVT VT = Op.getSimpleValueType();
17990   MVT EltVT = VT.getVectorElementType();
17991   unsigned VecSize = VT.getSizeInBits();
17992
17993   // Implement a lookup table in register by using an algorithm based on:
17994   // http://wm.ite.pl/articles/sse-popcount.html
17995   //
17996   // The general idea is that every lower byte nibble in the input vector is an
17997   // index into a in-register pre-computed pop count table. We then split up the
17998   // input vector in two new ones: (1) a vector with only the shifted-right
17999   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18000   // masked out higher ones) for each byte. PSHUB is used separately with both
18001   // to index the in-register table. Next, both are added and the result is a
18002   // i8 vector where each element contains the pop count for input byte.
18003   //
18004   // To obtain the pop count for elements != i8, we follow up with the same
18005   // approach and use additional tricks as described below.
18006   //
18007   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18008                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18009                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18010                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18011
18012   int NumByteElts = VecSize / 8;
18013   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18014   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18015   SmallVector<SDValue, 16> LUTVec;
18016   for (int i = 0; i < NumByteElts; ++i)
18017     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18018   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18019   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18020                                   DAG.getConstant(0x0F, DL, MVT::i8));
18021   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18022
18023   // High nibbles
18024   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18025   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18026   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18027
18028   // Low nibbles
18029   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18030
18031   // The input vector is used as the shuffle mask that index elements into the
18032   // LUT. After counting low and high nibbles, add the vector to obtain the
18033   // final pop count per i8 element.
18034   SDValue HighPopCnt =
18035       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18036   SDValue LowPopCnt =
18037       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18038   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18039
18040   if (EltVT == MVT::i8)
18041     return PopCnt;
18042
18043   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18044 }
18045
18046 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18047                                        const X86Subtarget *Subtarget,
18048                                        SelectionDAG &DAG) {
18049   MVT VT = Op.getSimpleValueType();
18050   assert(VT.is128BitVector() &&
18051          "Only 128-bit vector bitmath lowering supported.");
18052
18053   int VecSize = VT.getSizeInBits();
18054   MVT EltVT = VT.getVectorElementType();
18055   int Len = EltVT.getSizeInBits();
18056
18057   // This is the vectorized version of the "best" algorithm from
18058   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18059   // with a minor tweak to use a series of adds + shifts instead of vector
18060   // multiplications. Implemented for all integer vector types. We only use
18061   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18062   // much faster, even faster than using native popcnt instructions.
18063
18064   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18065     MVT VT = V.getSimpleValueType();
18066     SmallVector<SDValue, 32> Shifters(
18067         VT.getVectorNumElements(),
18068         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18069     return DAG.getNode(OpCode, DL, VT, V,
18070                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18071   };
18072   auto GetMask = [&](SDValue V, APInt Mask) {
18073     MVT VT = V.getSimpleValueType();
18074     SmallVector<SDValue, 32> Masks(
18075         VT.getVectorNumElements(),
18076         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18077     return DAG.getNode(ISD::AND, DL, VT, V,
18078                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18079   };
18080
18081   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18082   // x86, so set the SRL type to have elements at least i16 wide. This is
18083   // correct because all of our SRLs are followed immediately by a mask anyways
18084   // that handles any bits that sneak into the high bits of the byte elements.
18085   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18086
18087   SDValue V = Op;
18088
18089   // v = v - ((v >> 1) & 0x55555555...)
18090   SDValue Srl =
18091       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18092   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18093   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18094
18095   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18096   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18097   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18098   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18099   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18100
18101   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18102   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18103   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18104   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18105
18106   // At this point, V contains the byte-wise population count, and we are
18107   // merely doing a horizontal sum if necessary to get the wider element
18108   // counts.
18109   if (EltVT == MVT::i8)
18110     return V;
18111
18112   return LowerHorizontalByteSum(
18113       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18114       DAG);
18115 }
18116
18117 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18118                                 SelectionDAG &DAG) {
18119   MVT VT = Op.getSimpleValueType();
18120   // FIXME: Need to add AVX-512 support here!
18121   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18122          "Unknown CTPOP type to handle");
18123   SDLoc DL(Op.getNode());
18124   SDValue Op0 = Op.getOperand(0);
18125
18126   if (!Subtarget->hasSSSE3()) {
18127     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18128     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18129     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18130   }
18131
18132   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18133     unsigned NumElems = VT.getVectorNumElements();
18134
18135     // Extract each 128-bit vector, compute pop count and concat the result.
18136     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18137     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18138
18139     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18140                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18141                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18142   }
18143
18144   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18145 }
18146
18147 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18148                           SelectionDAG &DAG) {
18149   assert(Op.getValueType().isVector() &&
18150          "We only do custom lowering for vector population count.");
18151   return LowerVectorCTPOP(Op, Subtarget, DAG);
18152 }
18153
18154 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18155   SDNode *Node = Op.getNode();
18156   SDLoc dl(Node);
18157   EVT T = Node->getValueType(0);
18158   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18159                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18160   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18161                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18162                        Node->getOperand(0),
18163                        Node->getOperand(1), negOp,
18164                        cast<AtomicSDNode>(Node)->getMemOperand(),
18165                        cast<AtomicSDNode>(Node)->getOrdering(),
18166                        cast<AtomicSDNode>(Node)->getSynchScope());
18167 }
18168
18169 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18170   SDNode *Node = Op.getNode();
18171   SDLoc dl(Node);
18172   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18173
18174   // Convert seq_cst store -> xchg
18175   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18176   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18177   //        (The only way to get a 16-byte store is cmpxchg16b)
18178   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18179   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18180       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18181     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18182                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18183                                  Node->getOperand(0),
18184                                  Node->getOperand(1), Node->getOperand(2),
18185                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18186                                  cast<AtomicSDNode>(Node)->getOrdering(),
18187                                  cast<AtomicSDNode>(Node)->getSynchScope());
18188     return Swap.getValue(1);
18189   }
18190   // Other atomic stores have a simple pattern.
18191   return Op;
18192 }
18193
18194 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18195   EVT VT = Op.getNode()->getSimpleValueType(0);
18196
18197   // Let legalize expand this if it isn't a legal type yet.
18198   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18199     return SDValue();
18200
18201   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18202
18203   unsigned Opc;
18204   bool ExtraOp = false;
18205   switch (Op.getOpcode()) {
18206   default: llvm_unreachable("Invalid code");
18207   case ISD::ADDC: Opc = X86ISD::ADD; break;
18208   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18209   case ISD::SUBC: Opc = X86ISD::SUB; break;
18210   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18211   }
18212
18213   if (!ExtraOp)
18214     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18215                        Op.getOperand(1));
18216   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18217                      Op.getOperand(1), Op.getOperand(2));
18218 }
18219
18220 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18221                             SelectionDAG &DAG) {
18222   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18223
18224   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18225   // which returns the values as { float, float } (in XMM0) or
18226   // { double, double } (which is returned in XMM0, XMM1).
18227   SDLoc dl(Op);
18228   SDValue Arg = Op.getOperand(0);
18229   EVT ArgVT = Arg.getValueType();
18230   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18231
18232   TargetLowering::ArgListTy Args;
18233   TargetLowering::ArgListEntry Entry;
18234
18235   Entry.Node = Arg;
18236   Entry.Ty = ArgTy;
18237   Entry.isSExt = false;
18238   Entry.isZExt = false;
18239   Args.push_back(Entry);
18240
18241   bool isF64 = ArgVT == MVT::f64;
18242   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18243   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18244   // the results are returned via SRet in memory.
18245   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18246   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18247   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
18248
18249   Type *RetTy = isF64
18250     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18251     : (Type*)VectorType::get(ArgTy, 4);
18252
18253   TargetLowering::CallLoweringInfo CLI(DAG);
18254   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18255     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18256
18257   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18258
18259   if (isF64)
18260     // Returned in xmm0 and xmm1.
18261     return CallResult.first;
18262
18263   // Returned in bits 0:31 and 32:64 xmm0.
18264   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18265                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18266   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18267                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18268   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18269   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18270 }
18271
18272 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18273                              SelectionDAG &DAG) {
18274   assert(Subtarget->hasAVX512() &&
18275          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18276
18277   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18278   EVT VT = N->getValue().getValueType();
18279   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18280   SDLoc dl(Op);
18281
18282   // X86 scatter kills mask register, so its type should be added to
18283   // the list of return values
18284   if (N->getNumValues() == 1) {
18285     SDValue Index = N->getIndex();
18286     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18287         !Index.getValueType().is512BitVector())
18288       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18289
18290     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18291     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18292                       N->getOperand(3), Index };
18293
18294     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18295     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18296     return SDValue(NewScatter.getNode(), 0);
18297   }
18298   return Op;
18299 }
18300
18301 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18302                             SelectionDAG &DAG) {
18303   assert(Subtarget->hasAVX512() &&
18304          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18305
18306   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18307   EVT VT = Op.getValueType();
18308   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18309   SDLoc dl(Op);
18310
18311   SDValue Index = N->getIndex();
18312   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18313       !Index.getValueType().is512BitVector()) {
18314     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18315     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18316                       N->getOperand(3), Index };
18317     DAG.UpdateNodeOperands(N, Ops);
18318   }
18319   return Op;
18320 }
18321
18322 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18323                                                     SelectionDAG &DAG) const {
18324   // TODO: Eventually, the lowering of these nodes should be informed by or
18325   // deferred to the GC strategy for the function in which they appear. For
18326   // now, however, they must be lowered to something. Since they are logically
18327   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18328   // require special handling for these nodes), lower them as literal NOOPs for
18329   // the time being.
18330   SmallVector<SDValue, 2> Ops;
18331
18332   Ops.push_back(Op.getOperand(0));
18333   if (Op->getGluedNode())
18334     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18335
18336   SDLoc OpDL(Op);
18337   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18338   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18339
18340   return NOOP;
18341 }
18342
18343 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18344                                                   SelectionDAG &DAG) const {
18345   // TODO: Eventually, the lowering of these nodes should be informed by or
18346   // deferred to the GC strategy for the function in which they appear. For
18347   // now, however, they must be lowered to something. Since they are logically
18348   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18349   // require special handling for these nodes), lower them as literal NOOPs for
18350   // the time being.
18351   SmallVector<SDValue, 2> Ops;
18352
18353   Ops.push_back(Op.getOperand(0));
18354   if (Op->getGluedNode())
18355     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18356
18357   SDLoc OpDL(Op);
18358   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18359   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18360
18361   return NOOP;
18362 }
18363
18364 /// LowerOperation - Provide custom lowering hooks for some operations.
18365 ///
18366 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18367   switch (Op.getOpcode()) {
18368   default: llvm_unreachable("Should not custom lower this!");
18369   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18370   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18371     return LowerCMP_SWAP(Op, Subtarget, DAG);
18372   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18373   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18374   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18375   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18376   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18377   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18378   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18379   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18380   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18381   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18382   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18383   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18384   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18385   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18386   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18387   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18388   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18389   case ISD::SHL_PARTS:
18390   case ISD::SRA_PARTS:
18391   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18392   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18393   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18394   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18395   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18396   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18397   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18398   case ISD::SIGN_EXTEND_VECTOR_INREG:
18399     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18400   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18401   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18402   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18403   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18404   case ISD::FABS:
18405   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18406   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18407   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18408   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18409   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18410   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18411   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18412   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18413   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18414   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18415   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18416   case ISD::INTRINSIC_VOID:
18417   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18418   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18419   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18420   case ISD::FRAME_TO_ARGS_OFFSET:
18421                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18422   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18423   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18424   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18425   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18426   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18427   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18428   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18429   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18430   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18431   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18432   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18433   case ISD::UMUL_LOHI:
18434   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18435   case ISD::SRA:
18436   case ISD::SRL:
18437   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18438   case ISD::SADDO:
18439   case ISD::UADDO:
18440   case ISD::SSUBO:
18441   case ISD::USUBO:
18442   case ISD::SMULO:
18443   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18444   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18445   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18446   case ISD::ADDC:
18447   case ISD::ADDE:
18448   case ISD::SUBC:
18449   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18450   case ISD::ADD:                return LowerADD(Op, DAG);
18451   case ISD::SUB:                return LowerSUB(Op, DAG);
18452   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18453   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18454   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18455   case ISD::GC_TRANSITION_START:
18456                                 return LowerGC_TRANSITION_START(Op, DAG);
18457   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18458   }
18459 }
18460
18461 /// ReplaceNodeResults - Replace a node with an illegal result type
18462 /// with a new node built out of custom code.
18463 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18464                                            SmallVectorImpl<SDValue>&Results,
18465                                            SelectionDAG &DAG) const {
18466   SDLoc dl(N);
18467   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18468   switch (N->getOpcode()) {
18469   default:
18470     llvm_unreachable("Do not know how to custom type legalize this operation!");
18471   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18472   case X86ISD::FMINC:
18473   case X86ISD::FMIN:
18474   case X86ISD::FMAXC:
18475   case X86ISD::FMAX: {
18476     EVT VT = N->getValueType(0);
18477     if (VT != MVT::v2f32)
18478       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18479     SDValue UNDEF = DAG.getUNDEF(VT);
18480     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18481                               N->getOperand(0), UNDEF);
18482     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18483                               N->getOperand(1), UNDEF);
18484     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18485     return;
18486   }
18487   case ISD::SIGN_EXTEND_INREG:
18488   case ISD::ADDC:
18489   case ISD::ADDE:
18490   case ISD::SUBC:
18491   case ISD::SUBE:
18492     // We don't want to expand or promote these.
18493     return;
18494   case ISD::SDIV:
18495   case ISD::UDIV:
18496   case ISD::SREM:
18497   case ISD::UREM:
18498   case ISD::SDIVREM:
18499   case ISD::UDIVREM: {
18500     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18501     Results.push_back(V);
18502     return;
18503   }
18504   case ISD::FP_TO_SINT:
18505     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18506     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18507     if (N->getOperand(0).getValueType() == MVT::f16)
18508       break;
18509     // fallthrough
18510   case ISD::FP_TO_UINT: {
18511     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18512
18513     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18514       return;
18515
18516     std::pair<SDValue,SDValue> Vals =
18517         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18518     SDValue FIST = Vals.first, StackSlot = Vals.second;
18519     if (FIST.getNode()) {
18520       EVT VT = N->getValueType(0);
18521       // Return a load from the stack slot.
18522       if (StackSlot.getNode())
18523         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18524                                       MachinePointerInfo(),
18525                                       false, false, false, 0));
18526       else
18527         Results.push_back(FIST);
18528     }
18529     return;
18530   }
18531   case ISD::UINT_TO_FP: {
18532     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18533     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18534         N->getValueType(0) != MVT::v2f32)
18535       return;
18536     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18537                                  N->getOperand(0));
18538     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18539                                      MVT::f64);
18540     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18541     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18542                              DAG.getBitcast(MVT::v2i64, VBias));
18543     Or = DAG.getBitcast(MVT::v2f64, Or);
18544     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18545     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18546     return;
18547   }
18548   case ISD::FP_ROUND: {
18549     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18550         return;
18551     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18552     Results.push_back(V);
18553     return;
18554   }
18555   case ISD::FP_EXTEND: {
18556     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18557     // No other ValueType for FP_EXTEND should reach this point.
18558     assert(N->getValueType(0) == MVT::v2f32 &&
18559            "Do not know how to legalize this Node");
18560     return;
18561   }
18562   case ISD::INTRINSIC_W_CHAIN: {
18563     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18564     switch (IntNo) {
18565     default : llvm_unreachable("Do not know how to custom type "
18566                                "legalize this intrinsic operation!");
18567     case Intrinsic::x86_rdtsc:
18568       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18569                                      Results);
18570     case Intrinsic::x86_rdtscp:
18571       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18572                                      Results);
18573     case Intrinsic::x86_rdpmc:
18574       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18575     }
18576   }
18577   case ISD::READCYCLECOUNTER: {
18578     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18579                                    Results);
18580   }
18581   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18582     EVT T = N->getValueType(0);
18583     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18584     bool Regs64bit = T == MVT::i128;
18585     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18586     SDValue cpInL, cpInH;
18587     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18588                         DAG.getConstant(0, dl, HalfT));
18589     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18590                         DAG.getConstant(1, dl, HalfT));
18591     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18592                              Regs64bit ? X86::RAX : X86::EAX,
18593                              cpInL, SDValue());
18594     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18595                              Regs64bit ? X86::RDX : X86::EDX,
18596                              cpInH, cpInL.getValue(1));
18597     SDValue swapInL, swapInH;
18598     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18599                           DAG.getConstant(0, dl, HalfT));
18600     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18601                           DAG.getConstant(1, dl, HalfT));
18602     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18603                                Regs64bit ? X86::RBX : X86::EBX,
18604                                swapInL, cpInH.getValue(1));
18605     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18606                                Regs64bit ? X86::RCX : X86::ECX,
18607                                swapInH, swapInL.getValue(1));
18608     SDValue Ops[] = { swapInH.getValue(0),
18609                       N->getOperand(1),
18610                       swapInH.getValue(1) };
18611     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18612     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18613     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18614                                   X86ISD::LCMPXCHG8_DAG;
18615     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18616     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18617                                         Regs64bit ? X86::RAX : X86::EAX,
18618                                         HalfT, Result.getValue(1));
18619     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18620                                         Regs64bit ? X86::RDX : X86::EDX,
18621                                         HalfT, cpOutL.getValue(2));
18622     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18623
18624     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18625                                         MVT::i32, cpOutH.getValue(2));
18626     SDValue Success =
18627         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18628                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18629     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18630
18631     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18632     Results.push_back(Success);
18633     Results.push_back(EFLAGS.getValue(1));
18634     return;
18635   }
18636   case ISD::ATOMIC_SWAP:
18637   case ISD::ATOMIC_LOAD_ADD:
18638   case ISD::ATOMIC_LOAD_SUB:
18639   case ISD::ATOMIC_LOAD_AND:
18640   case ISD::ATOMIC_LOAD_OR:
18641   case ISD::ATOMIC_LOAD_XOR:
18642   case ISD::ATOMIC_LOAD_NAND:
18643   case ISD::ATOMIC_LOAD_MIN:
18644   case ISD::ATOMIC_LOAD_MAX:
18645   case ISD::ATOMIC_LOAD_UMIN:
18646   case ISD::ATOMIC_LOAD_UMAX:
18647   case ISD::ATOMIC_LOAD: {
18648     // Delegate to generic TypeLegalization. Situations we can really handle
18649     // should have already been dealt with by AtomicExpandPass.cpp.
18650     break;
18651   }
18652   case ISD::BITCAST: {
18653     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18654     EVT DstVT = N->getValueType(0);
18655     EVT SrcVT = N->getOperand(0)->getValueType(0);
18656
18657     if (SrcVT != MVT::f64 ||
18658         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18659       return;
18660
18661     unsigned NumElts = DstVT.getVectorNumElements();
18662     EVT SVT = DstVT.getVectorElementType();
18663     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18664     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18665                                    MVT::v2f64, N->getOperand(0));
18666     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18667
18668     if (ExperimentalVectorWideningLegalization) {
18669       // If we are legalizing vectors by widening, we already have the desired
18670       // legal vector type, just return it.
18671       Results.push_back(ToVecInt);
18672       return;
18673     }
18674
18675     SmallVector<SDValue, 8> Elts;
18676     for (unsigned i = 0, e = NumElts; i != e; ++i)
18677       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18678                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18679
18680     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18681   }
18682   }
18683 }
18684
18685 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18686   switch ((X86ISD::NodeType)Opcode) {
18687   case X86ISD::FIRST_NUMBER:       break;
18688   case X86ISD::BSF:                return "X86ISD::BSF";
18689   case X86ISD::BSR:                return "X86ISD::BSR";
18690   case X86ISD::SHLD:               return "X86ISD::SHLD";
18691   case X86ISD::SHRD:               return "X86ISD::SHRD";
18692   case X86ISD::FAND:               return "X86ISD::FAND";
18693   case X86ISD::FANDN:              return "X86ISD::FANDN";
18694   case X86ISD::FOR:                return "X86ISD::FOR";
18695   case X86ISD::FXOR:               return "X86ISD::FXOR";
18696   case X86ISD::FILD:               return "X86ISD::FILD";
18697   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18698   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18699   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18700   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18701   case X86ISD::FLD:                return "X86ISD::FLD";
18702   case X86ISD::FST:                return "X86ISD::FST";
18703   case X86ISD::CALL:               return "X86ISD::CALL";
18704   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18705   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18706   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18707   case X86ISD::BT:                 return "X86ISD::BT";
18708   case X86ISD::CMP:                return "X86ISD::CMP";
18709   case X86ISD::COMI:               return "X86ISD::COMI";
18710   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18711   case X86ISD::CMPM:               return "X86ISD::CMPM";
18712   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18713   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18714   case X86ISD::SETCC:              return "X86ISD::SETCC";
18715   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18716   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18717   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18718   case X86ISD::CMOV:               return "X86ISD::CMOV";
18719   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18720   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18721   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18722   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18723   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18724   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18725   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18726   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18727   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18728   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18729   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18730   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18731   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18732   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18733   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18734   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18735   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18736   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18737   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18738   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18739   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18740   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18741   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18742   case X86ISD::HADD:               return "X86ISD::HADD";
18743   case X86ISD::HSUB:               return "X86ISD::HSUB";
18744   case X86ISD::FHADD:              return "X86ISD::FHADD";
18745   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18746   case X86ISD::ABS:                return "X86ISD::ABS";
18747   case X86ISD::FMAX:               return "X86ISD::FMAX";
18748   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18749   case X86ISD::FMIN:               return "X86ISD::FMIN";
18750   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18751   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18752   case X86ISD::FMINC:              return "X86ISD::FMINC";
18753   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18754   case X86ISD::FRCP:               return "X86ISD::FRCP";
18755   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
18756   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
18757   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18758   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18759   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18760   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18761   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18762   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18763   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18764   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18765   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18766   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18767   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18768   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18769   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18770   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18771   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18772   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18773   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18774   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18775   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18776   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18777   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18778   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18779   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18780   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18781   case X86ISD::VSHL:               return "X86ISD::VSHL";
18782   case X86ISD::VSRL:               return "X86ISD::VSRL";
18783   case X86ISD::VSRA:               return "X86ISD::VSRA";
18784   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18785   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18786   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18787   case X86ISD::CMPP:               return "X86ISD::CMPP";
18788   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18789   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18790   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18791   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18792   case X86ISD::ADD:                return "X86ISD::ADD";
18793   case X86ISD::SUB:                return "X86ISD::SUB";
18794   case X86ISD::ADC:                return "X86ISD::ADC";
18795   case X86ISD::SBB:                return "X86ISD::SBB";
18796   case X86ISD::SMUL:               return "X86ISD::SMUL";
18797   case X86ISD::UMUL:               return "X86ISD::UMUL";
18798   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18799   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18800   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18801   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18802   case X86ISD::INC:                return "X86ISD::INC";
18803   case X86ISD::DEC:                return "X86ISD::DEC";
18804   case X86ISD::OR:                 return "X86ISD::OR";
18805   case X86ISD::XOR:                return "X86ISD::XOR";
18806   case X86ISD::AND:                return "X86ISD::AND";
18807   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18808   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18809   case X86ISD::PTEST:              return "X86ISD::PTEST";
18810   case X86ISD::TESTP:              return "X86ISD::TESTP";
18811   case X86ISD::TESTM:              return "X86ISD::TESTM";
18812   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18813   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18814   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18815   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18816   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18817   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18818   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18819   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18820   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18821   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18822   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
18823   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18824   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18825   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18826   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18827   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18828   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18829   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18830   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18831   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18832   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18833   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18834   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18835   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18836   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18837   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18838   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18839   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18840   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18841   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18842   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18843   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18844   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18845   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
18846   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
18847   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18848   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18849   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
18850   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18851   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18852   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18853   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18854   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18855   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18856   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18857   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18858   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18859   case X86ISD::SAHF:               return "X86ISD::SAHF";
18860   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18861   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18862   case X86ISD::FMADD:              return "X86ISD::FMADD";
18863   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18864   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18865   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18866   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18867   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18868   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18869   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18870   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18871   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18872   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18873   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18874   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18875   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18876   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18877   case X86ISD::XTEST:              return "X86ISD::XTEST";
18878   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18879   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18880   case X86ISD::SELECT:             return "X86ISD::SELECT";
18881   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18882   case X86ISD::RCP28:              return "X86ISD::RCP28";
18883   case X86ISD::EXP2:               return "X86ISD::EXP2";
18884   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18885   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18886   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18887   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18888   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18889   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
18890   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
18891   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
18892   case X86ISD::ADDS:               return "X86ISD::ADDS";
18893   case X86ISD::SUBS:               return "X86ISD::SUBS";
18894   case X86ISD::AVG:                return "X86ISD::AVG";
18895   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
18896   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
18897   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
18898   }
18899   return nullptr;
18900 }
18901
18902 // isLegalAddressingMode - Return true if the addressing mode represented
18903 // by AM is legal for this target, for a load/store of the specified type.
18904 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18905                                               Type *Ty,
18906                                               unsigned AS) const {
18907   // X86 supports extremely general addressing modes.
18908   CodeModel::Model M = getTargetMachine().getCodeModel();
18909   Reloc::Model R = getTargetMachine().getRelocationModel();
18910
18911   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18912   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18913     return false;
18914
18915   if (AM.BaseGV) {
18916     unsigned GVFlags =
18917       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18918
18919     // If a reference to this global requires an extra load, we can't fold it.
18920     if (isGlobalStubReference(GVFlags))
18921       return false;
18922
18923     // If BaseGV requires a register for the PIC base, we cannot also have a
18924     // BaseReg specified.
18925     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18926       return false;
18927
18928     // If lower 4G is not available, then we must use rip-relative addressing.
18929     if ((M != CodeModel::Small || R != Reloc::Static) &&
18930         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18931       return false;
18932   }
18933
18934   switch (AM.Scale) {
18935   case 0:
18936   case 1:
18937   case 2:
18938   case 4:
18939   case 8:
18940     // These scales always work.
18941     break;
18942   case 3:
18943   case 5:
18944   case 9:
18945     // These scales are formed with basereg+scalereg.  Only accept if there is
18946     // no basereg yet.
18947     if (AM.HasBaseReg)
18948       return false;
18949     break;
18950   default:  // Other stuff never works.
18951     return false;
18952   }
18953
18954   return true;
18955 }
18956
18957 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18958   unsigned Bits = Ty->getScalarSizeInBits();
18959
18960   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18961   // particularly cheaper than those without.
18962   if (Bits == 8)
18963     return false;
18964
18965   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18966   // variable shifts just as cheap as scalar ones.
18967   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18968     return false;
18969
18970   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18971   // fully general vector.
18972   return true;
18973 }
18974
18975 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18976   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18977     return false;
18978   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18979   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18980   return NumBits1 > NumBits2;
18981 }
18982
18983 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18984   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18985     return false;
18986
18987   if (!isTypeLegal(EVT::getEVT(Ty1)))
18988     return false;
18989
18990   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18991
18992   // Assuming the caller doesn't have a zeroext or signext return parameter,
18993   // truncation all the way down to i1 is valid.
18994   return true;
18995 }
18996
18997 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18998   return isInt<32>(Imm);
18999 }
19000
19001 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19002   // Can also use sub to handle negated immediates.
19003   return isInt<32>(Imm);
19004 }
19005
19006 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19007   if (!VT1.isInteger() || !VT2.isInteger())
19008     return false;
19009   unsigned NumBits1 = VT1.getSizeInBits();
19010   unsigned NumBits2 = VT2.getSizeInBits();
19011   return NumBits1 > NumBits2;
19012 }
19013
19014 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19015   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19016   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19017 }
19018
19019 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19020   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19021   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19022 }
19023
19024 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19025   EVT VT1 = Val.getValueType();
19026   if (isZExtFree(VT1, VT2))
19027     return true;
19028
19029   if (Val.getOpcode() != ISD::LOAD)
19030     return false;
19031
19032   if (!VT1.isSimple() || !VT1.isInteger() ||
19033       !VT2.isSimple() || !VT2.isInteger())
19034     return false;
19035
19036   switch (VT1.getSimpleVT().SimpleTy) {
19037   default: break;
19038   case MVT::i8:
19039   case MVT::i16:
19040   case MVT::i32:
19041     // X86 has 8, 16, and 32-bit zero-extending loads.
19042     return true;
19043   }
19044
19045   return false;
19046 }
19047
19048 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19049
19050 bool
19051 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19052   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19053     return false;
19054
19055   VT = VT.getScalarType();
19056
19057   if (!VT.isSimple())
19058     return false;
19059
19060   switch (VT.getSimpleVT().SimpleTy) {
19061   case MVT::f32:
19062   case MVT::f64:
19063     return true;
19064   default:
19065     break;
19066   }
19067
19068   return false;
19069 }
19070
19071 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19072   // i16 instructions are longer (0x66 prefix) and potentially slower.
19073   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19074 }
19075
19076 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19077 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19078 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19079 /// are assumed to be legal.
19080 bool
19081 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19082                                       EVT VT) const {
19083   if (!VT.isSimple())
19084     return false;
19085
19086   // Not for i1 vectors
19087   if (VT.getScalarType() == MVT::i1)
19088     return false;
19089
19090   // Very little shuffling can be done for 64-bit vectors right now.
19091   if (VT.getSizeInBits() == 64)
19092     return false;
19093
19094   // We only care that the types being shuffled are legal. The lowering can
19095   // handle any possible shuffle mask that results.
19096   return isTypeLegal(VT.getSimpleVT());
19097 }
19098
19099 bool
19100 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19101                                           EVT VT) const {
19102   // Just delegate to the generic legality, clear masks aren't special.
19103   return isShuffleMaskLegal(Mask, VT);
19104 }
19105
19106 //===----------------------------------------------------------------------===//
19107 //                           X86 Scheduler Hooks
19108 //===----------------------------------------------------------------------===//
19109
19110 /// Utility function to emit xbegin specifying the start of an RTM region.
19111 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19112                                      const TargetInstrInfo *TII) {
19113   DebugLoc DL = MI->getDebugLoc();
19114
19115   const BasicBlock *BB = MBB->getBasicBlock();
19116   MachineFunction::iterator I = MBB;
19117   ++I;
19118
19119   // For the v = xbegin(), we generate
19120   //
19121   // thisMBB:
19122   //  xbegin sinkMBB
19123   //
19124   // mainMBB:
19125   //  eax = -1
19126   //
19127   // sinkMBB:
19128   //  v = eax
19129
19130   MachineBasicBlock *thisMBB = MBB;
19131   MachineFunction *MF = MBB->getParent();
19132   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19133   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19134   MF->insert(I, mainMBB);
19135   MF->insert(I, sinkMBB);
19136
19137   // Transfer the remainder of BB and its successor edges to sinkMBB.
19138   sinkMBB->splice(sinkMBB->begin(), MBB,
19139                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19140   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19141
19142   // thisMBB:
19143   //  xbegin sinkMBB
19144   //  # fallthrough to mainMBB
19145   //  # abortion to sinkMBB
19146   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19147   thisMBB->addSuccessor(mainMBB);
19148   thisMBB->addSuccessor(sinkMBB);
19149
19150   // mainMBB:
19151   //  EAX = -1
19152   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19153   mainMBB->addSuccessor(sinkMBB);
19154
19155   // sinkMBB:
19156   // EAX is live into the sinkMBB
19157   sinkMBB->addLiveIn(X86::EAX);
19158   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19159           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19160     .addReg(X86::EAX);
19161
19162   MI->eraseFromParent();
19163   return sinkMBB;
19164 }
19165
19166 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19167 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19168 // in the .td file.
19169 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19170                                        const TargetInstrInfo *TII) {
19171   unsigned Opc;
19172   switch (MI->getOpcode()) {
19173   default: llvm_unreachable("illegal opcode!");
19174   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19175   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19176   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19177   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19178   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19179   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19180   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19181   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19182   }
19183
19184   DebugLoc dl = MI->getDebugLoc();
19185   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19186
19187   unsigned NumArgs = MI->getNumOperands();
19188   for (unsigned i = 1; i < NumArgs; ++i) {
19189     MachineOperand &Op = MI->getOperand(i);
19190     if (!(Op.isReg() && Op.isImplicit()))
19191       MIB.addOperand(Op);
19192   }
19193   if (MI->hasOneMemOperand())
19194     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19195
19196   BuildMI(*BB, MI, dl,
19197     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19198     .addReg(X86::XMM0);
19199
19200   MI->eraseFromParent();
19201   return BB;
19202 }
19203
19204 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19205 // defs in an instruction pattern
19206 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19207                                        const TargetInstrInfo *TII) {
19208   unsigned Opc;
19209   switch (MI->getOpcode()) {
19210   default: llvm_unreachable("illegal opcode!");
19211   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19212   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19213   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19214   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19215   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19216   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19217   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19218   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19219   }
19220
19221   DebugLoc dl = MI->getDebugLoc();
19222   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19223
19224   unsigned NumArgs = MI->getNumOperands(); // remove the results
19225   for (unsigned i = 1; i < NumArgs; ++i) {
19226     MachineOperand &Op = MI->getOperand(i);
19227     if (!(Op.isReg() && Op.isImplicit()))
19228       MIB.addOperand(Op);
19229   }
19230   if (MI->hasOneMemOperand())
19231     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19232
19233   BuildMI(*BB, MI, dl,
19234     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19235     .addReg(X86::ECX);
19236
19237   MI->eraseFromParent();
19238   return BB;
19239 }
19240
19241 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19242                                       const X86Subtarget *Subtarget) {
19243   DebugLoc dl = MI->getDebugLoc();
19244   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19245   // Address into RAX/EAX, other two args into ECX, EDX.
19246   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19247   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19248   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19249   for (int i = 0; i < X86::AddrNumOperands; ++i)
19250     MIB.addOperand(MI->getOperand(i));
19251
19252   unsigned ValOps = X86::AddrNumOperands;
19253   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19254     .addReg(MI->getOperand(ValOps).getReg());
19255   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19256     .addReg(MI->getOperand(ValOps+1).getReg());
19257
19258   // The instruction doesn't actually take any operands though.
19259   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19260
19261   MI->eraseFromParent(); // The pseudo is gone now.
19262   return BB;
19263 }
19264
19265 MachineBasicBlock *
19266 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19267                                                  MachineBasicBlock *MBB) const {
19268   // Emit va_arg instruction on X86-64.
19269
19270   // Operands to this pseudo-instruction:
19271   // 0  ) Output        : destination address (reg)
19272   // 1-5) Input         : va_list address (addr, i64mem)
19273   // 6  ) ArgSize       : Size (in bytes) of vararg type
19274   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19275   // 8  ) Align         : Alignment of type
19276   // 9  ) EFLAGS (implicit-def)
19277
19278   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19279   static_assert(X86::AddrNumOperands == 5,
19280                 "VAARG_64 assumes 5 address operands");
19281
19282   unsigned DestReg = MI->getOperand(0).getReg();
19283   MachineOperand &Base = MI->getOperand(1);
19284   MachineOperand &Scale = MI->getOperand(2);
19285   MachineOperand &Index = MI->getOperand(3);
19286   MachineOperand &Disp = MI->getOperand(4);
19287   MachineOperand &Segment = MI->getOperand(5);
19288   unsigned ArgSize = MI->getOperand(6).getImm();
19289   unsigned ArgMode = MI->getOperand(7).getImm();
19290   unsigned Align = MI->getOperand(8).getImm();
19291
19292   // Memory Reference
19293   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19294   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19295   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19296
19297   // Machine Information
19298   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19299   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19300   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19301   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19302   DebugLoc DL = MI->getDebugLoc();
19303
19304   // struct va_list {
19305   //   i32   gp_offset
19306   //   i32   fp_offset
19307   //   i64   overflow_area (address)
19308   //   i64   reg_save_area (address)
19309   // }
19310   // sizeof(va_list) = 24
19311   // alignment(va_list) = 8
19312
19313   unsigned TotalNumIntRegs = 6;
19314   unsigned TotalNumXMMRegs = 8;
19315   bool UseGPOffset = (ArgMode == 1);
19316   bool UseFPOffset = (ArgMode == 2);
19317   unsigned MaxOffset = TotalNumIntRegs * 8 +
19318                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19319
19320   /* Align ArgSize to a multiple of 8 */
19321   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19322   bool NeedsAlign = (Align > 8);
19323
19324   MachineBasicBlock *thisMBB = MBB;
19325   MachineBasicBlock *overflowMBB;
19326   MachineBasicBlock *offsetMBB;
19327   MachineBasicBlock *endMBB;
19328
19329   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19330   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19331   unsigned OffsetReg = 0;
19332
19333   if (!UseGPOffset && !UseFPOffset) {
19334     // If we only pull from the overflow region, we don't create a branch.
19335     // We don't need to alter control flow.
19336     OffsetDestReg = 0; // unused
19337     OverflowDestReg = DestReg;
19338
19339     offsetMBB = nullptr;
19340     overflowMBB = thisMBB;
19341     endMBB = thisMBB;
19342   } else {
19343     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19344     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19345     // If not, pull from overflow_area. (branch to overflowMBB)
19346     //
19347     //       thisMBB
19348     //         |     .
19349     //         |        .
19350     //     offsetMBB   overflowMBB
19351     //         |        .
19352     //         |     .
19353     //        endMBB
19354
19355     // Registers for the PHI in endMBB
19356     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19357     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19358
19359     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19360     MachineFunction *MF = MBB->getParent();
19361     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19362     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19363     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19364
19365     MachineFunction::iterator MBBIter = MBB;
19366     ++MBBIter;
19367
19368     // Insert the new basic blocks
19369     MF->insert(MBBIter, offsetMBB);
19370     MF->insert(MBBIter, overflowMBB);
19371     MF->insert(MBBIter, endMBB);
19372
19373     // Transfer the remainder of MBB and its successor edges to endMBB.
19374     endMBB->splice(endMBB->begin(), thisMBB,
19375                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19376     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19377
19378     // Make offsetMBB and overflowMBB successors of thisMBB
19379     thisMBB->addSuccessor(offsetMBB);
19380     thisMBB->addSuccessor(overflowMBB);
19381
19382     // endMBB is a successor of both offsetMBB and overflowMBB
19383     offsetMBB->addSuccessor(endMBB);
19384     overflowMBB->addSuccessor(endMBB);
19385
19386     // Load the offset value into a register
19387     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19388     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19389       .addOperand(Base)
19390       .addOperand(Scale)
19391       .addOperand(Index)
19392       .addDisp(Disp, UseFPOffset ? 4 : 0)
19393       .addOperand(Segment)
19394       .setMemRefs(MMOBegin, MMOEnd);
19395
19396     // Check if there is enough room left to pull this argument.
19397     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19398       .addReg(OffsetReg)
19399       .addImm(MaxOffset + 8 - ArgSizeA8);
19400
19401     // Branch to "overflowMBB" if offset >= max
19402     // Fall through to "offsetMBB" otherwise
19403     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19404       .addMBB(overflowMBB);
19405   }
19406
19407   // In offsetMBB, emit code to use the reg_save_area.
19408   if (offsetMBB) {
19409     assert(OffsetReg != 0);
19410
19411     // Read the reg_save_area address.
19412     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19413     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19414       .addOperand(Base)
19415       .addOperand(Scale)
19416       .addOperand(Index)
19417       .addDisp(Disp, 16)
19418       .addOperand(Segment)
19419       .setMemRefs(MMOBegin, MMOEnd);
19420
19421     // Zero-extend the offset
19422     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19423       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19424         .addImm(0)
19425         .addReg(OffsetReg)
19426         .addImm(X86::sub_32bit);
19427
19428     // Add the offset to the reg_save_area to get the final address.
19429     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19430       .addReg(OffsetReg64)
19431       .addReg(RegSaveReg);
19432
19433     // Compute the offset for the next argument
19434     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19435     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19436       .addReg(OffsetReg)
19437       .addImm(UseFPOffset ? 16 : 8);
19438
19439     // Store it back into the va_list.
19440     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19441       .addOperand(Base)
19442       .addOperand(Scale)
19443       .addOperand(Index)
19444       .addDisp(Disp, UseFPOffset ? 4 : 0)
19445       .addOperand(Segment)
19446       .addReg(NextOffsetReg)
19447       .setMemRefs(MMOBegin, MMOEnd);
19448
19449     // Jump to endMBB
19450     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19451       .addMBB(endMBB);
19452   }
19453
19454   //
19455   // Emit code to use overflow area
19456   //
19457
19458   // Load the overflow_area address into a register.
19459   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19460   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19461     .addOperand(Base)
19462     .addOperand(Scale)
19463     .addOperand(Index)
19464     .addDisp(Disp, 8)
19465     .addOperand(Segment)
19466     .setMemRefs(MMOBegin, MMOEnd);
19467
19468   // If we need to align it, do so. Otherwise, just copy the address
19469   // to OverflowDestReg.
19470   if (NeedsAlign) {
19471     // Align the overflow address
19472     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19473     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19474
19475     // aligned_addr = (addr + (align-1)) & ~(align-1)
19476     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19477       .addReg(OverflowAddrReg)
19478       .addImm(Align-1);
19479
19480     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19481       .addReg(TmpReg)
19482       .addImm(~(uint64_t)(Align-1));
19483   } else {
19484     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19485       .addReg(OverflowAddrReg);
19486   }
19487
19488   // Compute the next overflow address after this argument.
19489   // (the overflow address should be kept 8-byte aligned)
19490   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19491   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19492     .addReg(OverflowDestReg)
19493     .addImm(ArgSizeA8);
19494
19495   // Store the new overflow address.
19496   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19497     .addOperand(Base)
19498     .addOperand(Scale)
19499     .addOperand(Index)
19500     .addDisp(Disp, 8)
19501     .addOperand(Segment)
19502     .addReg(NextAddrReg)
19503     .setMemRefs(MMOBegin, MMOEnd);
19504
19505   // If we branched, emit the PHI to the front of endMBB.
19506   if (offsetMBB) {
19507     BuildMI(*endMBB, endMBB->begin(), DL,
19508             TII->get(X86::PHI), DestReg)
19509       .addReg(OffsetDestReg).addMBB(offsetMBB)
19510       .addReg(OverflowDestReg).addMBB(overflowMBB);
19511   }
19512
19513   // Erase the pseudo instruction
19514   MI->eraseFromParent();
19515
19516   return endMBB;
19517 }
19518
19519 MachineBasicBlock *
19520 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19521                                                  MachineInstr *MI,
19522                                                  MachineBasicBlock *MBB) const {
19523   // Emit code to save XMM registers to the stack. The ABI says that the
19524   // number of registers to save is given in %al, so it's theoretically
19525   // possible to do an indirect jump trick to avoid saving all of them,
19526   // however this code takes a simpler approach and just executes all
19527   // of the stores if %al is non-zero. It's less code, and it's probably
19528   // easier on the hardware branch predictor, and stores aren't all that
19529   // expensive anyway.
19530
19531   // Create the new basic blocks. One block contains all the XMM stores,
19532   // and one block is the final destination regardless of whether any
19533   // stores were performed.
19534   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19535   MachineFunction *F = MBB->getParent();
19536   MachineFunction::iterator MBBIter = MBB;
19537   ++MBBIter;
19538   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19539   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19540   F->insert(MBBIter, XMMSaveMBB);
19541   F->insert(MBBIter, EndMBB);
19542
19543   // Transfer the remainder of MBB and its successor edges to EndMBB.
19544   EndMBB->splice(EndMBB->begin(), MBB,
19545                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19546   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19547
19548   // The original block will now fall through to the XMM save block.
19549   MBB->addSuccessor(XMMSaveMBB);
19550   // The XMMSaveMBB will fall through to the end block.
19551   XMMSaveMBB->addSuccessor(EndMBB);
19552
19553   // Now add the instructions.
19554   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19555   DebugLoc DL = MI->getDebugLoc();
19556
19557   unsigned CountReg = MI->getOperand(0).getReg();
19558   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19559   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19560
19561   if (!Subtarget->isTargetWin64()) {
19562     // If %al is 0, branch around the XMM save block.
19563     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19564     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19565     MBB->addSuccessor(EndMBB);
19566   }
19567
19568   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19569   // that was just emitted, but clearly shouldn't be "saved".
19570   assert((MI->getNumOperands() <= 3 ||
19571           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19572           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19573          && "Expected last argument to be EFLAGS");
19574   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19575   // In the XMM save block, save all the XMM argument registers.
19576   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19577     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19578     MachineMemOperand *MMO =
19579       F->getMachineMemOperand(
19580           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19581         MachineMemOperand::MOStore,
19582         /*Size=*/16, /*Align=*/16);
19583     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19584       .addFrameIndex(RegSaveFrameIndex)
19585       .addImm(/*Scale=*/1)
19586       .addReg(/*IndexReg=*/0)
19587       .addImm(/*Disp=*/Offset)
19588       .addReg(/*Segment=*/0)
19589       .addReg(MI->getOperand(i).getReg())
19590       .addMemOperand(MMO);
19591   }
19592
19593   MI->eraseFromParent();   // The pseudo instruction is gone now.
19594
19595   return EndMBB;
19596 }
19597
19598 // The EFLAGS operand of SelectItr might be missing a kill marker
19599 // because there were multiple uses of EFLAGS, and ISel didn't know
19600 // which to mark. Figure out whether SelectItr should have had a
19601 // kill marker, and set it if it should. Returns the correct kill
19602 // marker value.
19603 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19604                                      MachineBasicBlock* BB,
19605                                      const TargetRegisterInfo* TRI) {
19606   // Scan forward through BB for a use/def of EFLAGS.
19607   MachineBasicBlock::iterator miI(std::next(SelectItr));
19608   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19609     const MachineInstr& mi = *miI;
19610     if (mi.readsRegister(X86::EFLAGS))
19611       return false;
19612     if (mi.definesRegister(X86::EFLAGS))
19613       break; // Should have kill-flag - update below.
19614   }
19615
19616   // If we hit the end of the block, check whether EFLAGS is live into a
19617   // successor.
19618   if (miI == BB->end()) {
19619     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19620                                           sEnd = BB->succ_end();
19621          sItr != sEnd; ++sItr) {
19622       MachineBasicBlock* succ = *sItr;
19623       if (succ->isLiveIn(X86::EFLAGS))
19624         return false;
19625     }
19626   }
19627
19628   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19629   // out. SelectMI should have a kill flag on EFLAGS.
19630   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19631   return true;
19632 }
19633
19634 MachineBasicBlock *
19635 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19636                                      MachineBasicBlock *BB) const {
19637   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19638   DebugLoc DL = MI->getDebugLoc();
19639
19640   // To "insert" a SELECT_CC instruction, we actually have to insert the
19641   // diamond control-flow pattern.  The incoming instruction knows the
19642   // destination vreg to set, the condition code register to branch on, the
19643   // true/false values to select between, and a branch opcode to use.
19644   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19645   MachineFunction::iterator It = BB;
19646   ++It;
19647
19648   //  thisMBB:
19649   //  ...
19650   //   TrueVal = ...
19651   //   cmpTY ccX, r1, r2
19652   //   bCC copy1MBB
19653   //   fallthrough --> copy0MBB
19654   MachineBasicBlock *thisMBB = BB;
19655   MachineFunction *F = BB->getParent();
19656
19657   // We also lower double CMOVs:
19658   //   (CMOV (CMOV F, T, cc1), T, cc2)
19659   // to two successives branches.  For that, we look for another CMOV as the
19660   // following instruction.
19661   //
19662   // Without this, we would add a PHI between the two jumps, which ends up
19663   // creating a few copies all around. For instance, for
19664   //
19665   //    (sitofp (zext (fcmp une)))
19666   //
19667   // we would generate:
19668   //
19669   //         ucomiss %xmm1, %xmm0
19670   //         movss  <1.0f>, %xmm0
19671   //         movaps  %xmm0, %xmm1
19672   //         jne     .LBB5_2
19673   //         xorps   %xmm1, %xmm1
19674   // .LBB5_2:
19675   //         jp      .LBB5_4
19676   //         movaps  %xmm1, %xmm0
19677   // .LBB5_4:
19678   //         retq
19679   //
19680   // because this custom-inserter would have generated:
19681   //
19682   //   A
19683   //   | \
19684   //   |  B
19685   //   | /
19686   //   C
19687   //   | \
19688   //   |  D
19689   //   | /
19690   //   E
19691   //
19692   // A: X = ...; Y = ...
19693   // B: empty
19694   // C: Z = PHI [X, A], [Y, B]
19695   // D: empty
19696   // E: PHI [X, C], [Z, D]
19697   //
19698   // If we lower both CMOVs in a single step, we can instead generate:
19699   //
19700   //   A
19701   //   | \
19702   //   |  C
19703   //   | /|
19704   //   |/ |
19705   //   |  |
19706   //   |  D
19707   //   | /
19708   //   E
19709   //
19710   // A: X = ...; Y = ...
19711   // D: empty
19712   // E: PHI [X, A], [X, C], [Y, D]
19713   //
19714   // Which, in our sitofp/fcmp example, gives us something like:
19715   //
19716   //         ucomiss %xmm1, %xmm0
19717   //         movss  <1.0f>, %xmm0
19718   //         jne     .LBB5_4
19719   //         jp      .LBB5_4
19720   //         xorps   %xmm0, %xmm0
19721   // .LBB5_4:
19722   //         retq
19723   //
19724   MachineInstr *NextCMOV = nullptr;
19725   MachineBasicBlock::iterator NextMIIt =
19726       std::next(MachineBasicBlock::iterator(MI));
19727   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19728       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19729       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19730     NextCMOV = &*NextMIIt;
19731
19732   MachineBasicBlock *jcc1MBB = nullptr;
19733
19734   // If we have a double CMOV, we lower it to two successive branches to
19735   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19736   if (NextCMOV) {
19737     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19738     F->insert(It, jcc1MBB);
19739     jcc1MBB->addLiveIn(X86::EFLAGS);
19740   }
19741
19742   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19743   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19744   F->insert(It, copy0MBB);
19745   F->insert(It, sinkMBB);
19746
19747   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19748   // live into the sink and copy blocks.
19749   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19750
19751   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19752   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19753       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19754     copy0MBB->addLiveIn(X86::EFLAGS);
19755     sinkMBB->addLiveIn(X86::EFLAGS);
19756   }
19757
19758   // Transfer the remainder of BB and its successor edges to sinkMBB.
19759   sinkMBB->splice(sinkMBB->begin(), BB,
19760                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19761   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19762
19763   // Add the true and fallthrough blocks as its successors.
19764   if (NextCMOV) {
19765     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19766     BB->addSuccessor(jcc1MBB);
19767
19768     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19769     // jump to the sinkMBB.
19770     jcc1MBB->addSuccessor(copy0MBB);
19771     jcc1MBB->addSuccessor(sinkMBB);
19772   } else {
19773     BB->addSuccessor(copy0MBB);
19774   }
19775
19776   // The true block target of the first (or only) branch is always sinkMBB.
19777   BB->addSuccessor(sinkMBB);
19778
19779   // Create the conditional branch instruction.
19780   unsigned Opc =
19781     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19782   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19783
19784   if (NextCMOV) {
19785     unsigned Opc2 = X86::GetCondBranchFromCond(
19786         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19787     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19788   }
19789
19790   //  copy0MBB:
19791   //   %FalseValue = ...
19792   //   # fallthrough to sinkMBB
19793   copy0MBB->addSuccessor(sinkMBB);
19794
19795   //  sinkMBB:
19796   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19797   //  ...
19798   MachineInstrBuilder MIB =
19799       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19800               MI->getOperand(0).getReg())
19801           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19802           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19803
19804   // If we have a double CMOV, the second Jcc provides the same incoming
19805   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19806   if (NextCMOV) {
19807     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19808     // Copy the PHI result to the register defined by the second CMOV.
19809     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19810             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19811         .addReg(MI->getOperand(0).getReg());
19812     NextCMOV->eraseFromParent();
19813   }
19814
19815   MI->eraseFromParent();   // The pseudo instruction is gone now.
19816   return sinkMBB;
19817 }
19818
19819 MachineBasicBlock *
19820 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19821                                         MachineBasicBlock *BB) const {
19822   MachineFunction *MF = BB->getParent();
19823   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19824   DebugLoc DL = MI->getDebugLoc();
19825   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19826
19827   assert(MF->shouldSplitStack());
19828
19829   const bool Is64Bit = Subtarget->is64Bit();
19830   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19831
19832   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19833   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19834
19835   // BB:
19836   //  ... [Till the alloca]
19837   // If stacklet is not large enough, jump to mallocMBB
19838   //
19839   // bumpMBB:
19840   //  Allocate by subtracting from RSP
19841   //  Jump to continueMBB
19842   //
19843   // mallocMBB:
19844   //  Allocate by call to runtime
19845   //
19846   // continueMBB:
19847   //  ...
19848   //  [rest of original BB]
19849   //
19850
19851   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19852   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19853   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19854
19855   MachineRegisterInfo &MRI = MF->getRegInfo();
19856   const TargetRegisterClass *AddrRegClass =
19857     getRegClassFor(getPointerTy());
19858
19859   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19860     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19861     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19862     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19863     sizeVReg = MI->getOperand(1).getReg(),
19864     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19865
19866   MachineFunction::iterator MBBIter = BB;
19867   ++MBBIter;
19868
19869   MF->insert(MBBIter, bumpMBB);
19870   MF->insert(MBBIter, mallocMBB);
19871   MF->insert(MBBIter, continueMBB);
19872
19873   continueMBB->splice(continueMBB->begin(), BB,
19874                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19875   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19876
19877   // Add code to the main basic block to check if the stack limit has been hit,
19878   // and if so, jump to mallocMBB otherwise to bumpMBB.
19879   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19880   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19881     .addReg(tmpSPVReg).addReg(sizeVReg);
19882   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19883     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19884     .addReg(SPLimitVReg);
19885   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19886
19887   // bumpMBB simply decreases the stack pointer, since we know the current
19888   // stacklet has enough space.
19889   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19890     .addReg(SPLimitVReg);
19891   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19892     .addReg(SPLimitVReg);
19893   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19894
19895   // Calls into a routine in libgcc to allocate more space from the heap.
19896   const uint32_t *RegMask =
19897       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19898   if (IsLP64) {
19899     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19900       .addReg(sizeVReg);
19901     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19902       .addExternalSymbol("__morestack_allocate_stack_space")
19903       .addRegMask(RegMask)
19904       .addReg(X86::RDI, RegState::Implicit)
19905       .addReg(X86::RAX, RegState::ImplicitDefine);
19906   } else if (Is64Bit) {
19907     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19908       .addReg(sizeVReg);
19909     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19910       .addExternalSymbol("__morestack_allocate_stack_space")
19911       .addRegMask(RegMask)
19912       .addReg(X86::EDI, RegState::Implicit)
19913       .addReg(X86::EAX, RegState::ImplicitDefine);
19914   } else {
19915     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19916       .addImm(12);
19917     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19918     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19919       .addExternalSymbol("__morestack_allocate_stack_space")
19920       .addRegMask(RegMask)
19921       .addReg(X86::EAX, RegState::ImplicitDefine);
19922   }
19923
19924   if (!Is64Bit)
19925     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19926       .addImm(16);
19927
19928   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19929     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19930   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19931
19932   // Set up the CFG correctly.
19933   BB->addSuccessor(bumpMBB);
19934   BB->addSuccessor(mallocMBB);
19935   mallocMBB->addSuccessor(continueMBB);
19936   bumpMBB->addSuccessor(continueMBB);
19937
19938   // Take care of the PHI nodes.
19939   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19940           MI->getOperand(0).getReg())
19941     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19942     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19943
19944   // Delete the original pseudo instruction.
19945   MI->eraseFromParent();
19946
19947   // And we're done.
19948   return continueMBB;
19949 }
19950
19951 MachineBasicBlock *
19952 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19953                                         MachineBasicBlock *BB) const {
19954   DebugLoc DL = MI->getDebugLoc();
19955
19956   assert(!Subtarget->isTargetMachO());
19957
19958   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
19959                                                     DL);
19960
19961   MI->eraseFromParent();   // The pseudo instruction is gone now.
19962   return BB;
19963 }
19964
19965 MachineBasicBlock *
19966 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19967                                       MachineBasicBlock *BB) const {
19968   // This is pretty easy.  We're taking the value that we received from
19969   // our load from the relocation, sticking it in either RDI (x86-64)
19970   // or EAX and doing an indirect call.  The return value will then
19971   // be in the normal return register.
19972   MachineFunction *F = BB->getParent();
19973   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19974   DebugLoc DL = MI->getDebugLoc();
19975
19976   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19977   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19978
19979   // Get a register mask for the lowered call.
19980   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19981   // proper register mask.
19982   const uint32_t *RegMask =
19983       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19984   if (Subtarget->is64Bit()) {
19985     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19986                                       TII->get(X86::MOV64rm), X86::RDI)
19987     .addReg(X86::RIP)
19988     .addImm(0).addReg(0)
19989     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19990                       MI->getOperand(3).getTargetFlags())
19991     .addReg(0);
19992     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19993     addDirectMem(MIB, X86::RDI);
19994     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19995   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19996     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19997                                       TII->get(X86::MOV32rm), X86::EAX)
19998     .addReg(0)
19999     .addImm(0).addReg(0)
20000     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20001                       MI->getOperand(3).getTargetFlags())
20002     .addReg(0);
20003     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20004     addDirectMem(MIB, X86::EAX);
20005     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20006   } else {
20007     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20008                                       TII->get(X86::MOV32rm), X86::EAX)
20009     .addReg(TII->getGlobalBaseReg(F))
20010     .addImm(0).addReg(0)
20011     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20012                       MI->getOperand(3).getTargetFlags())
20013     .addReg(0);
20014     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20015     addDirectMem(MIB, X86::EAX);
20016     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20017   }
20018
20019   MI->eraseFromParent(); // The pseudo instruction is gone now.
20020   return BB;
20021 }
20022
20023 MachineBasicBlock *
20024 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20025                                     MachineBasicBlock *MBB) const {
20026   DebugLoc DL = MI->getDebugLoc();
20027   MachineFunction *MF = MBB->getParent();
20028   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20029   MachineRegisterInfo &MRI = MF->getRegInfo();
20030
20031   const BasicBlock *BB = MBB->getBasicBlock();
20032   MachineFunction::iterator I = MBB;
20033   ++I;
20034
20035   // Memory Reference
20036   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20037   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20038
20039   unsigned DstReg;
20040   unsigned MemOpndSlot = 0;
20041
20042   unsigned CurOp = 0;
20043
20044   DstReg = MI->getOperand(CurOp++).getReg();
20045   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20046   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20047   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20048   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20049
20050   MemOpndSlot = CurOp;
20051
20052   MVT PVT = getPointerTy();
20053   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20054          "Invalid Pointer Size!");
20055
20056   // For v = setjmp(buf), we generate
20057   //
20058   // thisMBB:
20059   //  buf[LabelOffset] = restoreMBB
20060   //  SjLjSetup restoreMBB
20061   //
20062   // mainMBB:
20063   //  v_main = 0
20064   //
20065   // sinkMBB:
20066   //  v = phi(main, restore)
20067   //
20068   // restoreMBB:
20069   //  if base pointer being used, load it from frame
20070   //  v_restore = 1
20071
20072   MachineBasicBlock *thisMBB = MBB;
20073   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20074   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20075   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20076   MF->insert(I, mainMBB);
20077   MF->insert(I, sinkMBB);
20078   MF->push_back(restoreMBB);
20079
20080   MachineInstrBuilder MIB;
20081
20082   // Transfer the remainder of BB and its successor edges to sinkMBB.
20083   sinkMBB->splice(sinkMBB->begin(), MBB,
20084                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20085   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20086
20087   // thisMBB:
20088   unsigned PtrStoreOpc = 0;
20089   unsigned LabelReg = 0;
20090   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20091   Reloc::Model RM = MF->getTarget().getRelocationModel();
20092   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20093                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20094
20095   // Prepare IP either in reg or imm.
20096   if (!UseImmLabel) {
20097     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20098     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20099     LabelReg = MRI.createVirtualRegister(PtrRC);
20100     if (Subtarget->is64Bit()) {
20101       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20102               .addReg(X86::RIP)
20103               .addImm(0)
20104               .addReg(0)
20105               .addMBB(restoreMBB)
20106               .addReg(0);
20107     } else {
20108       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20109       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20110               .addReg(XII->getGlobalBaseReg(MF))
20111               .addImm(0)
20112               .addReg(0)
20113               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20114               .addReg(0);
20115     }
20116   } else
20117     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20118   // Store IP
20119   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20120   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20121     if (i == X86::AddrDisp)
20122       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20123     else
20124       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20125   }
20126   if (!UseImmLabel)
20127     MIB.addReg(LabelReg);
20128   else
20129     MIB.addMBB(restoreMBB);
20130   MIB.setMemRefs(MMOBegin, MMOEnd);
20131   // Setup
20132   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20133           .addMBB(restoreMBB);
20134
20135   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20136   MIB.addRegMask(RegInfo->getNoPreservedMask());
20137   thisMBB->addSuccessor(mainMBB);
20138   thisMBB->addSuccessor(restoreMBB);
20139
20140   // mainMBB:
20141   //  EAX = 0
20142   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20143   mainMBB->addSuccessor(sinkMBB);
20144
20145   // sinkMBB:
20146   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20147           TII->get(X86::PHI), DstReg)
20148     .addReg(mainDstReg).addMBB(mainMBB)
20149     .addReg(restoreDstReg).addMBB(restoreMBB);
20150
20151   // restoreMBB:
20152   if (RegInfo->hasBasePointer(*MF)) {
20153     const bool Uses64BitFramePtr =
20154         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20155     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20156     X86FI->setRestoreBasePointer(MF);
20157     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20158     unsigned BasePtr = RegInfo->getBaseRegister();
20159     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20160     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20161                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20162       .setMIFlag(MachineInstr::FrameSetup);
20163   }
20164   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20165   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20166   restoreMBB->addSuccessor(sinkMBB);
20167
20168   MI->eraseFromParent();
20169   return sinkMBB;
20170 }
20171
20172 MachineBasicBlock *
20173 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20174                                      MachineBasicBlock *MBB) const {
20175   DebugLoc DL = MI->getDebugLoc();
20176   MachineFunction *MF = MBB->getParent();
20177   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20178   MachineRegisterInfo &MRI = MF->getRegInfo();
20179
20180   // Memory Reference
20181   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20182   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20183
20184   MVT PVT = getPointerTy();
20185   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20186          "Invalid Pointer Size!");
20187
20188   const TargetRegisterClass *RC =
20189     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20190   unsigned Tmp = MRI.createVirtualRegister(RC);
20191   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20192   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20193   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20194   unsigned SP = RegInfo->getStackRegister();
20195
20196   MachineInstrBuilder MIB;
20197
20198   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20199   const int64_t SPOffset = 2 * PVT.getStoreSize();
20200
20201   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20202   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20203
20204   // Reload FP
20205   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20206   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20207     MIB.addOperand(MI->getOperand(i));
20208   MIB.setMemRefs(MMOBegin, MMOEnd);
20209   // Reload IP
20210   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20211   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20212     if (i == X86::AddrDisp)
20213       MIB.addDisp(MI->getOperand(i), LabelOffset);
20214     else
20215       MIB.addOperand(MI->getOperand(i));
20216   }
20217   MIB.setMemRefs(MMOBegin, MMOEnd);
20218   // Reload SP
20219   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20220   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20221     if (i == X86::AddrDisp)
20222       MIB.addDisp(MI->getOperand(i), SPOffset);
20223     else
20224       MIB.addOperand(MI->getOperand(i));
20225   }
20226   MIB.setMemRefs(MMOBegin, MMOEnd);
20227   // Jump
20228   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20229
20230   MI->eraseFromParent();
20231   return MBB;
20232 }
20233
20234 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20235 // accumulator loops. Writing back to the accumulator allows the coalescer
20236 // to remove extra copies in the loop.
20237 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20238 MachineBasicBlock *
20239 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20240                                  MachineBasicBlock *MBB) const {
20241   MachineOperand &AddendOp = MI->getOperand(3);
20242
20243   // Bail out early if the addend isn't a register - we can't switch these.
20244   if (!AddendOp.isReg())
20245     return MBB;
20246
20247   MachineFunction &MF = *MBB->getParent();
20248   MachineRegisterInfo &MRI = MF.getRegInfo();
20249
20250   // Check whether the addend is defined by a PHI:
20251   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20252   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20253   if (!AddendDef.isPHI())
20254     return MBB;
20255
20256   // Look for the following pattern:
20257   // loop:
20258   //   %addend = phi [%entry, 0], [%loop, %result]
20259   //   ...
20260   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20261
20262   // Replace with:
20263   //   loop:
20264   //   %addend = phi [%entry, 0], [%loop, %result]
20265   //   ...
20266   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20267
20268   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20269     assert(AddendDef.getOperand(i).isReg());
20270     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20271     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20272     if (&PHISrcInst == MI) {
20273       // Found a matching instruction.
20274       unsigned NewFMAOpc = 0;
20275       switch (MI->getOpcode()) {
20276         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20277         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20278         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20279         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20280         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20281         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20282         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20283         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20284         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20285         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20286         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20287         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20288         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20289         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20290         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20291         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20292         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20293         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20294         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20295         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20296
20297         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20298         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20299         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20300         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20301         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20302         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20303         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20304         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20305         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20306         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20307         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20308         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20309         default: llvm_unreachable("Unrecognized FMA variant.");
20310       }
20311
20312       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20313       MachineInstrBuilder MIB =
20314         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20315         .addOperand(MI->getOperand(0))
20316         .addOperand(MI->getOperand(3))
20317         .addOperand(MI->getOperand(2))
20318         .addOperand(MI->getOperand(1));
20319       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20320       MI->eraseFromParent();
20321     }
20322   }
20323
20324   return MBB;
20325 }
20326
20327 MachineBasicBlock *
20328 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20329                                                MachineBasicBlock *BB) const {
20330   switch (MI->getOpcode()) {
20331   default: llvm_unreachable("Unexpected instr type to insert");
20332   case X86::TAILJMPd64:
20333   case X86::TAILJMPr64:
20334   case X86::TAILJMPm64:
20335   case X86::TAILJMPd64_REX:
20336   case X86::TAILJMPr64_REX:
20337   case X86::TAILJMPm64_REX:
20338     llvm_unreachable("TAILJMP64 would not be touched here.");
20339   case X86::TCRETURNdi64:
20340   case X86::TCRETURNri64:
20341   case X86::TCRETURNmi64:
20342     return BB;
20343   case X86::WIN_ALLOCA:
20344     return EmitLoweredWinAlloca(MI, BB);
20345   case X86::SEG_ALLOCA_32:
20346   case X86::SEG_ALLOCA_64:
20347     return EmitLoweredSegAlloca(MI, BB);
20348   case X86::TLSCall_32:
20349   case X86::TLSCall_64:
20350     return EmitLoweredTLSCall(MI, BB);
20351   case X86::CMOV_GR8:
20352   case X86::CMOV_FR32:
20353   case X86::CMOV_FR64:
20354   case X86::CMOV_V4F32:
20355   case X86::CMOV_V2F64:
20356   case X86::CMOV_V2I64:
20357   case X86::CMOV_V8F32:
20358   case X86::CMOV_V4F64:
20359   case X86::CMOV_V4I64:
20360   case X86::CMOV_V16F32:
20361   case X86::CMOV_V8F64:
20362   case X86::CMOV_V8I64:
20363   case X86::CMOV_GR16:
20364   case X86::CMOV_GR32:
20365   case X86::CMOV_RFP32:
20366   case X86::CMOV_RFP64:
20367   case X86::CMOV_RFP80:
20368   case X86::CMOV_V8I1:
20369   case X86::CMOV_V16I1:
20370   case X86::CMOV_V32I1:
20371   case X86::CMOV_V64I1:
20372     return EmitLoweredSelect(MI, BB);
20373
20374   case X86::FP32_TO_INT16_IN_MEM:
20375   case X86::FP32_TO_INT32_IN_MEM:
20376   case X86::FP32_TO_INT64_IN_MEM:
20377   case X86::FP64_TO_INT16_IN_MEM:
20378   case X86::FP64_TO_INT32_IN_MEM:
20379   case X86::FP64_TO_INT64_IN_MEM:
20380   case X86::FP80_TO_INT16_IN_MEM:
20381   case X86::FP80_TO_INT32_IN_MEM:
20382   case X86::FP80_TO_INT64_IN_MEM: {
20383     MachineFunction *F = BB->getParent();
20384     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20385     DebugLoc DL = MI->getDebugLoc();
20386
20387     // Change the floating point control register to use "round towards zero"
20388     // mode when truncating to an integer value.
20389     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20390     addFrameReference(BuildMI(*BB, MI, DL,
20391                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20392
20393     // Load the old value of the high byte of the control word...
20394     unsigned OldCW =
20395       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20396     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20397                       CWFrameIdx);
20398
20399     // Set the high part to be round to zero...
20400     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20401       .addImm(0xC7F);
20402
20403     // Reload the modified control word now...
20404     addFrameReference(BuildMI(*BB, MI, DL,
20405                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20406
20407     // Restore the memory image of control word to original value
20408     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20409       .addReg(OldCW);
20410
20411     // Get the X86 opcode to use.
20412     unsigned Opc;
20413     switch (MI->getOpcode()) {
20414     default: llvm_unreachable("illegal opcode!");
20415     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20416     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20417     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20418     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20419     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20420     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20421     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20422     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20423     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20424     }
20425
20426     X86AddressMode AM;
20427     MachineOperand &Op = MI->getOperand(0);
20428     if (Op.isReg()) {
20429       AM.BaseType = X86AddressMode::RegBase;
20430       AM.Base.Reg = Op.getReg();
20431     } else {
20432       AM.BaseType = X86AddressMode::FrameIndexBase;
20433       AM.Base.FrameIndex = Op.getIndex();
20434     }
20435     Op = MI->getOperand(1);
20436     if (Op.isImm())
20437       AM.Scale = Op.getImm();
20438     Op = MI->getOperand(2);
20439     if (Op.isImm())
20440       AM.IndexReg = Op.getImm();
20441     Op = MI->getOperand(3);
20442     if (Op.isGlobal()) {
20443       AM.GV = Op.getGlobal();
20444     } else {
20445       AM.Disp = Op.getImm();
20446     }
20447     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20448                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20449
20450     // Reload the original control word now.
20451     addFrameReference(BuildMI(*BB, MI, DL,
20452                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20453
20454     MI->eraseFromParent();   // The pseudo instruction is gone now.
20455     return BB;
20456   }
20457     // String/text processing lowering.
20458   case X86::PCMPISTRM128REG:
20459   case X86::VPCMPISTRM128REG:
20460   case X86::PCMPISTRM128MEM:
20461   case X86::VPCMPISTRM128MEM:
20462   case X86::PCMPESTRM128REG:
20463   case X86::VPCMPESTRM128REG:
20464   case X86::PCMPESTRM128MEM:
20465   case X86::VPCMPESTRM128MEM:
20466     assert(Subtarget->hasSSE42() &&
20467            "Target must have SSE4.2 or AVX features enabled");
20468     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20469
20470   // String/text processing lowering.
20471   case X86::PCMPISTRIREG:
20472   case X86::VPCMPISTRIREG:
20473   case X86::PCMPISTRIMEM:
20474   case X86::VPCMPISTRIMEM:
20475   case X86::PCMPESTRIREG:
20476   case X86::VPCMPESTRIREG:
20477   case X86::PCMPESTRIMEM:
20478   case X86::VPCMPESTRIMEM:
20479     assert(Subtarget->hasSSE42() &&
20480            "Target must have SSE4.2 or AVX features enabled");
20481     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20482
20483   // Thread synchronization.
20484   case X86::MONITOR:
20485     return EmitMonitor(MI, BB, Subtarget);
20486
20487   // xbegin
20488   case X86::XBEGIN:
20489     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20490
20491   case X86::VASTART_SAVE_XMM_REGS:
20492     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20493
20494   case X86::VAARG_64:
20495     return EmitVAARG64WithCustomInserter(MI, BB);
20496
20497   case X86::EH_SjLj_SetJmp32:
20498   case X86::EH_SjLj_SetJmp64:
20499     return emitEHSjLjSetJmp(MI, BB);
20500
20501   case X86::EH_SjLj_LongJmp32:
20502   case X86::EH_SjLj_LongJmp64:
20503     return emitEHSjLjLongJmp(MI, BB);
20504
20505   case TargetOpcode::STATEPOINT:
20506     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20507     // this point in the process.  We diverge later.
20508     return emitPatchPoint(MI, BB);
20509
20510   case TargetOpcode::STACKMAP:
20511   case TargetOpcode::PATCHPOINT:
20512     return emitPatchPoint(MI, BB);
20513
20514   case X86::VFMADDPDr213r:
20515   case X86::VFMADDPSr213r:
20516   case X86::VFMADDSDr213r:
20517   case X86::VFMADDSSr213r:
20518   case X86::VFMSUBPDr213r:
20519   case X86::VFMSUBPSr213r:
20520   case X86::VFMSUBSDr213r:
20521   case X86::VFMSUBSSr213r:
20522   case X86::VFNMADDPDr213r:
20523   case X86::VFNMADDPSr213r:
20524   case X86::VFNMADDSDr213r:
20525   case X86::VFNMADDSSr213r:
20526   case X86::VFNMSUBPDr213r:
20527   case X86::VFNMSUBPSr213r:
20528   case X86::VFNMSUBSDr213r:
20529   case X86::VFNMSUBSSr213r:
20530   case X86::VFMADDSUBPDr213r:
20531   case X86::VFMADDSUBPSr213r:
20532   case X86::VFMSUBADDPDr213r:
20533   case X86::VFMSUBADDPSr213r:
20534   case X86::VFMADDPDr213rY:
20535   case X86::VFMADDPSr213rY:
20536   case X86::VFMSUBPDr213rY:
20537   case X86::VFMSUBPSr213rY:
20538   case X86::VFNMADDPDr213rY:
20539   case X86::VFNMADDPSr213rY:
20540   case X86::VFNMSUBPDr213rY:
20541   case X86::VFNMSUBPSr213rY:
20542   case X86::VFMADDSUBPDr213rY:
20543   case X86::VFMADDSUBPSr213rY:
20544   case X86::VFMSUBADDPDr213rY:
20545   case X86::VFMSUBADDPSr213rY:
20546     return emitFMA3Instr(MI, BB);
20547   }
20548 }
20549
20550 //===----------------------------------------------------------------------===//
20551 //                           X86 Optimization Hooks
20552 //===----------------------------------------------------------------------===//
20553
20554 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20555                                                       APInt &KnownZero,
20556                                                       APInt &KnownOne,
20557                                                       const SelectionDAG &DAG,
20558                                                       unsigned Depth) const {
20559   unsigned BitWidth = KnownZero.getBitWidth();
20560   unsigned Opc = Op.getOpcode();
20561   assert((Opc >= ISD::BUILTIN_OP_END ||
20562           Opc == ISD::INTRINSIC_WO_CHAIN ||
20563           Opc == ISD::INTRINSIC_W_CHAIN ||
20564           Opc == ISD::INTRINSIC_VOID) &&
20565          "Should use MaskedValueIsZero if you don't know whether Op"
20566          " is a target node!");
20567
20568   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20569   switch (Opc) {
20570   default: break;
20571   case X86ISD::ADD:
20572   case X86ISD::SUB:
20573   case X86ISD::ADC:
20574   case X86ISD::SBB:
20575   case X86ISD::SMUL:
20576   case X86ISD::UMUL:
20577   case X86ISD::INC:
20578   case X86ISD::DEC:
20579   case X86ISD::OR:
20580   case X86ISD::XOR:
20581   case X86ISD::AND:
20582     // These nodes' second result is a boolean.
20583     if (Op.getResNo() == 0)
20584       break;
20585     // Fallthrough
20586   case X86ISD::SETCC:
20587     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20588     break;
20589   case ISD::INTRINSIC_WO_CHAIN: {
20590     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20591     unsigned NumLoBits = 0;
20592     switch (IntId) {
20593     default: break;
20594     case Intrinsic::x86_sse_movmsk_ps:
20595     case Intrinsic::x86_avx_movmsk_ps_256:
20596     case Intrinsic::x86_sse2_movmsk_pd:
20597     case Intrinsic::x86_avx_movmsk_pd_256:
20598     case Intrinsic::x86_mmx_pmovmskb:
20599     case Intrinsic::x86_sse2_pmovmskb_128:
20600     case Intrinsic::x86_avx2_pmovmskb: {
20601       // High bits of movmskp{s|d}, pmovmskb are known zero.
20602       switch (IntId) {
20603         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20604         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20605         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20606         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20607         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20608         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20609         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20610         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20611       }
20612       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20613       break;
20614     }
20615     }
20616     break;
20617   }
20618   }
20619 }
20620
20621 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20622   SDValue Op,
20623   const SelectionDAG &,
20624   unsigned Depth) const {
20625   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20626   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20627     return Op.getValueType().getScalarType().getSizeInBits();
20628
20629   // Fallback case.
20630   return 1;
20631 }
20632
20633 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20634 /// node is a GlobalAddress + offset.
20635 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20636                                        const GlobalValue* &GA,
20637                                        int64_t &Offset) const {
20638   if (N->getOpcode() == X86ISD::Wrapper) {
20639     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20640       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20641       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20642       return true;
20643     }
20644   }
20645   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20646 }
20647
20648 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20649 /// same as extracting the high 128-bit part of 256-bit vector and then
20650 /// inserting the result into the low part of a new 256-bit vector
20651 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20652   EVT VT = SVOp->getValueType(0);
20653   unsigned NumElems = VT.getVectorNumElements();
20654
20655   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20656   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20657     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20658         SVOp->getMaskElt(j) >= 0)
20659       return false;
20660
20661   return true;
20662 }
20663
20664 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20665 /// same as extracting the low 128-bit part of 256-bit vector and then
20666 /// inserting the result into the high part of a new 256-bit vector
20667 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20668   EVT VT = SVOp->getValueType(0);
20669   unsigned NumElems = VT.getVectorNumElements();
20670
20671   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20672   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20673     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20674         SVOp->getMaskElt(j) >= 0)
20675       return false;
20676
20677   return true;
20678 }
20679
20680 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20681 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20682                                         TargetLowering::DAGCombinerInfo &DCI,
20683                                         const X86Subtarget* Subtarget) {
20684   SDLoc dl(N);
20685   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20686   SDValue V1 = SVOp->getOperand(0);
20687   SDValue V2 = SVOp->getOperand(1);
20688   EVT VT = SVOp->getValueType(0);
20689   unsigned NumElems = VT.getVectorNumElements();
20690
20691   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20692       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20693     //
20694     //                   0,0,0,...
20695     //                      |
20696     //    V      UNDEF    BUILD_VECTOR    UNDEF
20697     //     \      /           \           /
20698     //  CONCAT_VECTOR         CONCAT_VECTOR
20699     //         \                  /
20700     //          \                /
20701     //          RESULT: V + zero extended
20702     //
20703     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20704         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20705         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20706       return SDValue();
20707
20708     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20709       return SDValue();
20710
20711     // To match the shuffle mask, the first half of the mask should
20712     // be exactly the first vector, and all the rest a splat with the
20713     // first element of the second one.
20714     for (unsigned i = 0; i != NumElems/2; ++i)
20715       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20716           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20717         return SDValue();
20718
20719     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20720     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20721       if (Ld->hasNUsesOfValue(1, 0)) {
20722         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20723         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20724         SDValue ResNode =
20725           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20726                                   Ld->getMemoryVT(),
20727                                   Ld->getPointerInfo(),
20728                                   Ld->getAlignment(),
20729                                   false/*isVolatile*/, true/*ReadMem*/,
20730                                   false/*WriteMem*/);
20731
20732         // Make sure the newly-created LOAD is in the same position as Ld in
20733         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20734         // and update uses of Ld's output chain to use the TokenFactor.
20735         if (Ld->hasAnyUseOfValue(1)) {
20736           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20737                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20738           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20739           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20740                                  SDValue(ResNode.getNode(), 1));
20741         }
20742
20743         return DAG.getBitcast(VT, ResNode);
20744       }
20745     }
20746
20747     // Emit a zeroed vector and insert the desired subvector on its
20748     // first half.
20749     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20750     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20751     return DCI.CombineTo(N, InsV);
20752   }
20753
20754   //===--------------------------------------------------------------------===//
20755   // Combine some shuffles into subvector extracts and inserts:
20756   //
20757
20758   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20759   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20760     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20761     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20762     return DCI.CombineTo(N, InsV);
20763   }
20764
20765   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20766   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20767     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20768     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20769     return DCI.CombineTo(N, InsV);
20770   }
20771
20772   return SDValue();
20773 }
20774
20775 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20776 /// possible.
20777 ///
20778 /// This is the leaf of the recursive combinine below. When we have found some
20779 /// chain of single-use x86 shuffle instructions and accumulated the combined
20780 /// shuffle mask represented by them, this will try to pattern match that mask
20781 /// into either a single instruction if there is a special purpose instruction
20782 /// for this operation, or into a PSHUFB instruction which is a fully general
20783 /// instruction but should only be used to replace chains over a certain depth.
20784 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20785                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20786                                    TargetLowering::DAGCombinerInfo &DCI,
20787                                    const X86Subtarget *Subtarget) {
20788   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20789
20790   // Find the operand that enters the chain. Note that multiple uses are OK
20791   // here, we're not going to remove the operand we find.
20792   SDValue Input = Op.getOperand(0);
20793   while (Input.getOpcode() == ISD::BITCAST)
20794     Input = Input.getOperand(0);
20795
20796   MVT VT = Input.getSimpleValueType();
20797   MVT RootVT = Root.getSimpleValueType();
20798   SDLoc DL(Root);
20799
20800   // Just remove no-op shuffle masks.
20801   if (Mask.size() == 1) {
20802     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20803                   /*AddTo*/ true);
20804     return true;
20805   }
20806
20807   // Use the float domain if the operand type is a floating point type.
20808   bool FloatDomain = VT.isFloatingPoint();
20809
20810   // For floating point shuffles, we don't have free copies in the shuffle
20811   // instructions or the ability to load as part of the instruction, so
20812   // canonicalize their shuffles to UNPCK or MOV variants.
20813   //
20814   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20815   // vectors because it can have a load folded into it that UNPCK cannot. This
20816   // doesn't preclude something switching to the shorter encoding post-RA.
20817   //
20818   // FIXME: Should teach these routines about AVX vector widths.
20819   if (FloatDomain && VT.getSizeInBits() == 128) {
20820     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20821       bool Lo = Mask.equals({0, 0});
20822       unsigned Shuffle;
20823       MVT ShuffleVT;
20824       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20825       // is no slower than UNPCKLPD but has the option to fold the input operand
20826       // into even an unaligned memory load.
20827       if (Lo && Subtarget->hasSSE3()) {
20828         Shuffle = X86ISD::MOVDDUP;
20829         ShuffleVT = MVT::v2f64;
20830       } else {
20831         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20832         // than the UNPCK variants.
20833         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20834         ShuffleVT = MVT::v4f32;
20835       }
20836       if (Depth == 1 && Root->getOpcode() == Shuffle)
20837         return false; // Nothing to do!
20838       Op = DAG.getBitcast(ShuffleVT, Input);
20839       DCI.AddToWorklist(Op.getNode());
20840       if (Shuffle == X86ISD::MOVDDUP)
20841         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20842       else
20843         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20844       DCI.AddToWorklist(Op.getNode());
20845       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20846                     /*AddTo*/ true);
20847       return true;
20848     }
20849     if (Subtarget->hasSSE3() &&
20850         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20851       bool Lo = Mask.equals({0, 0, 2, 2});
20852       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20853       MVT ShuffleVT = MVT::v4f32;
20854       if (Depth == 1 && Root->getOpcode() == Shuffle)
20855         return false; // Nothing to do!
20856       Op = DAG.getBitcast(ShuffleVT, Input);
20857       DCI.AddToWorklist(Op.getNode());
20858       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20859       DCI.AddToWorklist(Op.getNode());
20860       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20861                     /*AddTo*/ true);
20862       return true;
20863     }
20864     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20865       bool Lo = Mask.equals({0, 0, 1, 1});
20866       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20867       MVT ShuffleVT = MVT::v4f32;
20868       if (Depth == 1 && Root->getOpcode() == Shuffle)
20869         return false; // Nothing to do!
20870       Op = DAG.getBitcast(ShuffleVT, Input);
20871       DCI.AddToWorklist(Op.getNode());
20872       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20873       DCI.AddToWorklist(Op.getNode());
20874       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20875                     /*AddTo*/ true);
20876       return true;
20877     }
20878   }
20879
20880   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20881   // variants as none of these have single-instruction variants that are
20882   // superior to the UNPCK formulation.
20883   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20884       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20885        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20886        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20887        Mask.equals(
20888            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20889     bool Lo = Mask[0] == 0;
20890     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20891     if (Depth == 1 && Root->getOpcode() == Shuffle)
20892       return false; // Nothing to do!
20893     MVT ShuffleVT;
20894     switch (Mask.size()) {
20895     case 8:
20896       ShuffleVT = MVT::v8i16;
20897       break;
20898     case 16:
20899       ShuffleVT = MVT::v16i8;
20900       break;
20901     default:
20902       llvm_unreachable("Impossible mask size!");
20903     };
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   // Don't try to re-form single instruction chains under any circumstances now
20914   // that we've done encoding canonicalization for them.
20915   if (Depth < 2)
20916     return false;
20917
20918   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20919   // can replace them with a single PSHUFB instruction profitably. Intel's
20920   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20921   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20922   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20923     SmallVector<SDValue, 16> PSHUFBMask;
20924     int NumBytes = VT.getSizeInBits() / 8;
20925     int Ratio = NumBytes / Mask.size();
20926     for (int i = 0; i < NumBytes; ++i) {
20927       if (Mask[i / Ratio] == SM_SentinelUndef) {
20928         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20929         continue;
20930       }
20931       int M = Mask[i / Ratio] != SM_SentinelZero
20932                   ? Ratio * Mask[i / Ratio] + i % Ratio
20933                   : 255;
20934       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20935     }
20936     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20937     Op = DAG.getBitcast(ByteVT, Input);
20938     DCI.AddToWorklist(Op.getNode());
20939     SDValue PSHUFBMaskOp =
20940         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20941     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20942     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20943     DCI.AddToWorklist(Op.getNode());
20944     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20945                   /*AddTo*/ true);
20946     return true;
20947   }
20948
20949   // Failed to find any combines.
20950   return false;
20951 }
20952
20953 /// \brief Fully generic combining of x86 shuffle instructions.
20954 ///
20955 /// This should be the last combine run over the x86 shuffle instructions. Once
20956 /// they have been fully optimized, this will recursively consider all chains
20957 /// of single-use shuffle instructions, build a generic model of the cumulative
20958 /// shuffle operation, and check for simpler instructions which implement this
20959 /// operation. We use this primarily for two purposes:
20960 ///
20961 /// 1) Collapse generic shuffles to specialized single instructions when
20962 ///    equivalent. In most cases, this is just an encoding size win, but
20963 ///    sometimes we will collapse multiple generic shuffles into a single
20964 ///    special-purpose shuffle.
20965 /// 2) Look for sequences of shuffle instructions with 3 or more total
20966 ///    instructions, and replace them with the slightly more expensive SSSE3
20967 ///    PSHUFB instruction if available. We do this as the last combining step
20968 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20969 ///    a suitable short sequence of other instructions. The PHUFB will either
20970 ///    use a register or have to read from memory and so is slightly (but only
20971 ///    slightly) more expensive than the other shuffle instructions.
20972 ///
20973 /// Because this is inherently a quadratic operation (for each shuffle in
20974 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20975 /// This should never be an issue in practice as the shuffle lowering doesn't
20976 /// produce sequences of more than 8 instructions.
20977 ///
20978 /// FIXME: We will currently miss some cases where the redundant shuffling
20979 /// would simplify under the threshold for PSHUFB formation because of
20980 /// combine-ordering. To fix this, we should do the redundant instruction
20981 /// combining in this recursive walk.
20982 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20983                                           ArrayRef<int> RootMask,
20984                                           int Depth, bool HasPSHUFB,
20985                                           SelectionDAG &DAG,
20986                                           TargetLowering::DAGCombinerInfo &DCI,
20987                                           const X86Subtarget *Subtarget) {
20988   // Bound the depth of our recursive combine because this is ultimately
20989   // quadratic in nature.
20990   if (Depth > 8)
20991     return false;
20992
20993   // Directly rip through bitcasts to find the underlying operand.
20994   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20995     Op = Op.getOperand(0);
20996
20997   MVT VT = Op.getSimpleValueType();
20998   if (!VT.isVector())
20999     return false; // Bail if we hit a non-vector.
21000
21001   assert(Root.getSimpleValueType().isVector() &&
21002          "Shuffles operate on vector types!");
21003   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21004          "Can only combine shuffles of the same vector register size.");
21005
21006   if (!isTargetShuffle(Op.getOpcode()))
21007     return false;
21008   SmallVector<int, 16> OpMask;
21009   bool IsUnary;
21010   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21011   // We only can combine unary shuffles which we can decode the mask for.
21012   if (!HaveMask || !IsUnary)
21013     return false;
21014
21015   assert(VT.getVectorNumElements() == OpMask.size() &&
21016          "Different mask size from vector size!");
21017   assert(((RootMask.size() > OpMask.size() &&
21018            RootMask.size() % OpMask.size() == 0) ||
21019           (OpMask.size() > RootMask.size() &&
21020            OpMask.size() % RootMask.size() == 0) ||
21021           OpMask.size() == RootMask.size()) &&
21022          "The smaller number of elements must divide the larger.");
21023   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21024   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21025   assert(((RootRatio == 1 && OpRatio == 1) ||
21026           (RootRatio == 1) != (OpRatio == 1)) &&
21027          "Must not have a ratio for both incoming and op masks!");
21028
21029   SmallVector<int, 16> Mask;
21030   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21031
21032   // Merge this shuffle operation's mask into our accumulated mask. Note that
21033   // this shuffle's mask will be the first applied to the input, followed by the
21034   // root mask to get us all the way to the root value arrangement. The reason
21035   // for this order is that we are recursing up the operation chain.
21036   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21037     int RootIdx = i / RootRatio;
21038     if (RootMask[RootIdx] < 0) {
21039       // This is a zero or undef lane, we're done.
21040       Mask.push_back(RootMask[RootIdx]);
21041       continue;
21042     }
21043
21044     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21045     int OpIdx = RootMaskedIdx / OpRatio;
21046     if (OpMask[OpIdx] < 0) {
21047       // The incoming lanes are zero or undef, it doesn't matter which ones we
21048       // are using.
21049       Mask.push_back(OpMask[OpIdx]);
21050       continue;
21051     }
21052
21053     // Ok, we have non-zero lanes, map them through.
21054     Mask.push_back(OpMask[OpIdx] * OpRatio +
21055                    RootMaskedIdx % OpRatio);
21056   }
21057
21058   // See if we can recurse into the operand to combine more things.
21059   switch (Op.getOpcode()) {
21060     case X86ISD::PSHUFB:
21061       HasPSHUFB = true;
21062     case X86ISD::PSHUFD:
21063     case X86ISD::PSHUFHW:
21064     case X86ISD::PSHUFLW:
21065       if (Op.getOperand(0).hasOneUse() &&
21066           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21067                                         HasPSHUFB, DAG, DCI, Subtarget))
21068         return true;
21069       break;
21070
21071     case X86ISD::UNPCKL:
21072     case X86ISD::UNPCKH:
21073       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21074       // We can't check for single use, we have to check that this shuffle is the only user.
21075       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21076           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21077                                         HasPSHUFB, DAG, DCI, Subtarget))
21078           return true;
21079       break;
21080   }
21081
21082   // Minor canonicalization of the accumulated shuffle mask to make it easier
21083   // to match below. All this does is detect masks with squential pairs of
21084   // elements, and shrink them to the half-width mask. It does this in a loop
21085   // so it will reduce the size of the mask to the minimal width mask which
21086   // performs an equivalent shuffle.
21087   SmallVector<int, 16> WidenedMask;
21088   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21089     Mask = std::move(WidenedMask);
21090     WidenedMask.clear();
21091   }
21092
21093   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21094                                 Subtarget);
21095 }
21096
21097 /// \brief Get the PSHUF-style mask from PSHUF node.
21098 ///
21099 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21100 /// PSHUF-style masks that can be reused with such instructions.
21101 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21102   MVT VT = N.getSimpleValueType();
21103   SmallVector<int, 4> Mask;
21104   bool IsUnary;
21105   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21106   (void)HaveMask;
21107   assert(HaveMask);
21108
21109   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21110   // matter. Check that the upper masks are repeats and remove them.
21111   if (VT.getSizeInBits() > 128) {
21112     int LaneElts = 128 / VT.getScalarSizeInBits();
21113 #ifndef NDEBUG
21114     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21115       for (int j = 0; j < LaneElts; ++j)
21116         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21117                "Mask doesn't repeat in high 128-bit lanes!");
21118 #endif
21119     Mask.resize(LaneElts);
21120   }
21121
21122   switch (N.getOpcode()) {
21123   case X86ISD::PSHUFD:
21124     return Mask;
21125   case X86ISD::PSHUFLW:
21126     Mask.resize(4);
21127     return Mask;
21128   case X86ISD::PSHUFHW:
21129     Mask.erase(Mask.begin(), Mask.begin() + 4);
21130     for (int &M : Mask)
21131       M -= 4;
21132     return Mask;
21133   default:
21134     llvm_unreachable("No valid shuffle instruction found!");
21135   }
21136 }
21137
21138 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21139 ///
21140 /// We walk up the chain and look for a combinable shuffle, skipping over
21141 /// shuffles that we could hoist this shuffle's transformation past without
21142 /// altering anything.
21143 static SDValue
21144 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21145                              SelectionDAG &DAG,
21146                              TargetLowering::DAGCombinerInfo &DCI) {
21147   assert(N.getOpcode() == X86ISD::PSHUFD &&
21148          "Called with something other than an x86 128-bit half shuffle!");
21149   SDLoc DL(N);
21150
21151   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21152   // of the shuffles in the chain so that we can form a fresh chain to replace
21153   // this one.
21154   SmallVector<SDValue, 8> Chain;
21155   SDValue V = N.getOperand(0);
21156   for (; V.hasOneUse(); V = V.getOperand(0)) {
21157     switch (V.getOpcode()) {
21158     default:
21159       return SDValue(); // Nothing combined!
21160
21161     case ISD::BITCAST:
21162       // Skip bitcasts as we always know the type for the target specific
21163       // instructions.
21164       continue;
21165
21166     case X86ISD::PSHUFD:
21167       // Found another dword shuffle.
21168       break;
21169
21170     case X86ISD::PSHUFLW:
21171       // Check that the low words (being shuffled) are the identity in the
21172       // dword shuffle, and the high words are self-contained.
21173       if (Mask[0] != 0 || Mask[1] != 1 ||
21174           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21175         return SDValue();
21176
21177       Chain.push_back(V);
21178       continue;
21179
21180     case X86ISD::PSHUFHW:
21181       // Check that the high words (being shuffled) are the identity in the
21182       // dword shuffle, and the low words are self-contained.
21183       if (Mask[2] != 2 || Mask[3] != 3 ||
21184           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21185         return SDValue();
21186
21187       Chain.push_back(V);
21188       continue;
21189
21190     case X86ISD::UNPCKL:
21191     case X86ISD::UNPCKH:
21192       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21193       // shuffle into a preceding word shuffle.
21194       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21195           V.getSimpleValueType().getScalarType() != MVT::i16)
21196         return SDValue();
21197
21198       // Search for a half-shuffle which we can combine with.
21199       unsigned CombineOp =
21200           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21201       if (V.getOperand(0) != V.getOperand(1) ||
21202           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21203         return SDValue();
21204       Chain.push_back(V);
21205       V = V.getOperand(0);
21206       do {
21207         switch (V.getOpcode()) {
21208         default:
21209           return SDValue(); // Nothing to combine.
21210
21211         case X86ISD::PSHUFLW:
21212         case X86ISD::PSHUFHW:
21213           if (V.getOpcode() == CombineOp)
21214             break;
21215
21216           Chain.push_back(V);
21217
21218           // Fallthrough!
21219         case ISD::BITCAST:
21220           V = V.getOperand(0);
21221           continue;
21222         }
21223         break;
21224       } while (V.hasOneUse());
21225       break;
21226     }
21227     // Break out of the loop if we break out of the switch.
21228     break;
21229   }
21230
21231   if (!V.hasOneUse())
21232     // We fell out of the loop without finding a viable combining instruction.
21233     return SDValue();
21234
21235   // Merge this node's mask and our incoming mask.
21236   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21237   for (int &M : Mask)
21238     M = VMask[M];
21239   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21240                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21241
21242   // Rebuild the chain around this new shuffle.
21243   while (!Chain.empty()) {
21244     SDValue W = Chain.pop_back_val();
21245
21246     if (V.getValueType() != W.getOperand(0).getValueType())
21247       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21248
21249     switch (W.getOpcode()) {
21250     default:
21251       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21252
21253     case X86ISD::UNPCKL:
21254     case X86ISD::UNPCKH:
21255       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21256       break;
21257
21258     case X86ISD::PSHUFD:
21259     case X86ISD::PSHUFLW:
21260     case X86ISD::PSHUFHW:
21261       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21262       break;
21263     }
21264   }
21265   if (V.getValueType() != N.getValueType())
21266     V = DAG.getBitcast(N.getValueType(), V);
21267
21268   // Return the new chain to replace N.
21269   return V;
21270 }
21271
21272 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21273 ///
21274 /// We walk up the chain, skipping shuffles of the other half and looking
21275 /// through shuffles which switch halves trying to find a shuffle of the same
21276 /// pair of dwords.
21277 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21278                                         SelectionDAG &DAG,
21279                                         TargetLowering::DAGCombinerInfo &DCI) {
21280   assert(
21281       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21282       "Called with something other than an x86 128-bit half shuffle!");
21283   SDLoc DL(N);
21284   unsigned CombineOpcode = N.getOpcode();
21285
21286   // Walk up a single-use chain looking for a combinable shuffle.
21287   SDValue V = N.getOperand(0);
21288   for (; V.hasOneUse(); V = V.getOperand(0)) {
21289     switch (V.getOpcode()) {
21290     default:
21291       return false; // Nothing combined!
21292
21293     case ISD::BITCAST:
21294       // Skip bitcasts as we always know the type for the target specific
21295       // instructions.
21296       continue;
21297
21298     case X86ISD::PSHUFLW:
21299     case X86ISD::PSHUFHW:
21300       if (V.getOpcode() == CombineOpcode)
21301         break;
21302
21303       // Other-half shuffles are no-ops.
21304       continue;
21305     }
21306     // Break out of the loop if we break out of the switch.
21307     break;
21308   }
21309
21310   if (!V.hasOneUse())
21311     // We fell out of the loop without finding a viable combining instruction.
21312     return false;
21313
21314   // Combine away the bottom node as its shuffle will be accumulated into
21315   // a preceding shuffle.
21316   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21317
21318   // Record the old value.
21319   SDValue Old = V;
21320
21321   // Merge this node's mask and our incoming mask (adjusted to account for all
21322   // the pshufd instructions encountered).
21323   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21324   for (int &M : Mask)
21325     M = VMask[M];
21326   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21327                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21328
21329   // Check that the shuffles didn't cancel each other out. If not, we need to
21330   // combine to the new one.
21331   if (Old != V)
21332     // Replace the combinable shuffle with the combined one, updating all users
21333     // so that we re-evaluate the chain here.
21334     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21335
21336   return true;
21337 }
21338
21339 /// \brief Try to combine x86 target specific shuffles.
21340 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21341                                            TargetLowering::DAGCombinerInfo &DCI,
21342                                            const X86Subtarget *Subtarget) {
21343   SDLoc DL(N);
21344   MVT VT = N.getSimpleValueType();
21345   SmallVector<int, 4> Mask;
21346
21347   switch (N.getOpcode()) {
21348   case X86ISD::PSHUFD:
21349   case X86ISD::PSHUFLW:
21350   case X86ISD::PSHUFHW:
21351     Mask = getPSHUFShuffleMask(N);
21352     assert(Mask.size() == 4);
21353     break;
21354   default:
21355     return SDValue();
21356   }
21357
21358   // Nuke no-op shuffles that show up after combining.
21359   if (isNoopShuffleMask(Mask))
21360     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21361
21362   // Look for simplifications involving one or two shuffle instructions.
21363   SDValue V = N.getOperand(0);
21364   switch (N.getOpcode()) {
21365   default:
21366     break;
21367   case X86ISD::PSHUFLW:
21368   case X86ISD::PSHUFHW:
21369     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21370
21371     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21372       return SDValue(); // We combined away this shuffle, so we're done.
21373
21374     // See if this reduces to a PSHUFD which is no more expensive and can
21375     // combine with more operations. Note that it has to at least flip the
21376     // dwords as otherwise it would have been removed as a no-op.
21377     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21378       int DMask[] = {0, 1, 2, 3};
21379       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21380       DMask[DOffset + 0] = DOffset + 1;
21381       DMask[DOffset + 1] = DOffset + 0;
21382       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21383       V = DAG.getBitcast(DVT, V);
21384       DCI.AddToWorklist(V.getNode());
21385       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21386                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21387       DCI.AddToWorklist(V.getNode());
21388       return DAG.getBitcast(VT, V);
21389     }
21390
21391     // Look for shuffle patterns which can be implemented as a single unpack.
21392     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21393     // only works when we have a PSHUFD followed by two half-shuffles.
21394     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21395         (V.getOpcode() == X86ISD::PSHUFLW ||
21396          V.getOpcode() == X86ISD::PSHUFHW) &&
21397         V.getOpcode() != N.getOpcode() &&
21398         V.hasOneUse()) {
21399       SDValue D = V.getOperand(0);
21400       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21401         D = D.getOperand(0);
21402       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21403         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21404         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21405         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21406         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21407         int WordMask[8];
21408         for (int i = 0; i < 4; ++i) {
21409           WordMask[i + NOffset] = Mask[i] + NOffset;
21410           WordMask[i + VOffset] = VMask[i] + VOffset;
21411         }
21412         // Map the word mask through the DWord mask.
21413         int MappedMask[8];
21414         for (int i = 0; i < 8; ++i)
21415           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21416         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21417             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21418           // We can replace all three shuffles with an unpack.
21419           V = DAG.getBitcast(VT, D.getOperand(0));
21420           DCI.AddToWorklist(V.getNode());
21421           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21422                                                 : X86ISD::UNPCKH,
21423                              DL, VT, V, V);
21424         }
21425       }
21426     }
21427
21428     break;
21429
21430   case X86ISD::PSHUFD:
21431     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21432       return NewN;
21433
21434     break;
21435   }
21436
21437   return SDValue();
21438 }
21439
21440 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21441 ///
21442 /// We combine this directly on the abstract vector shuffle nodes so it is
21443 /// easier to generically match. We also insert dummy vector shuffle nodes for
21444 /// the operands which explicitly discard the lanes which are unused by this
21445 /// operation to try to flow through the rest of the combiner the fact that
21446 /// they're unused.
21447 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21448   SDLoc DL(N);
21449   EVT VT = N->getValueType(0);
21450
21451   // We only handle target-independent shuffles.
21452   // FIXME: It would be easy and harmless to use the target shuffle mask
21453   // extraction tool to support more.
21454   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21455     return SDValue();
21456
21457   auto *SVN = cast<ShuffleVectorSDNode>(N);
21458   ArrayRef<int> Mask = SVN->getMask();
21459   SDValue V1 = N->getOperand(0);
21460   SDValue V2 = N->getOperand(1);
21461
21462   // We require the first shuffle operand to be the SUB node, and the second to
21463   // be the ADD node.
21464   // FIXME: We should support the commuted patterns.
21465   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21466     return SDValue();
21467
21468   // If there are other uses of these operations we can't fold them.
21469   if (!V1->hasOneUse() || !V2->hasOneUse())
21470     return SDValue();
21471
21472   // Ensure that both operations have the same operands. Note that we can
21473   // commute the FADD operands.
21474   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21475   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21476       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21477     return SDValue();
21478
21479   // We're looking for blends between FADD and FSUB nodes. We insist on these
21480   // nodes being lined up in a specific expected pattern.
21481   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21482         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21483         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21484     return SDValue();
21485
21486   // Only specific types are legal at this point, assert so we notice if and
21487   // when these change.
21488   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21489           VT == MVT::v4f64) &&
21490          "Unknown vector type encountered!");
21491
21492   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21493 }
21494
21495 /// PerformShuffleCombine - Performs several different shuffle combines.
21496 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21497                                      TargetLowering::DAGCombinerInfo &DCI,
21498                                      const X86Subtarget *Subtarget) {
21499   SDLoc dl(N);
21500   SDValue N0 = N->getOperand(0);
21501   SDValue N1 = N->getOperand(1);
21502   EVT VT = N->getValueType(0);
21503
21504   // Don't create instructions with illegal types after legalize types has run.
21505   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21506   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21507     return SDValue();
21508
21509   // If we have legalized the vector types, look for blends of FADD and FSUB
21510   // nodes that we can fuse into an ADDSUB node.
21511   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21512     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21513       return AddSub;
21514
21515   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21516   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21517       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21518     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21519
21520   // During Type Legalization, when promoting illegal vector types,
21521   // the backend might introduce new shuffle dag nodes and bitcasts.
21522   //
21523   // This code performs the following transformation:
21524   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21525   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21526   //
21527   // We do this only if both the bitcast and the BINOP dag nodes have
21528   // one use. Also, perform this transformation only if the new binary
21529   // operation is legal. This is to avoid introducing dag nodes that
21530   // potentially need to be further expanded (or custom lowered) into a
21531   // less optimal sequence of dag nodes.
21532   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21533       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21534       N0.getOpcode() == ISD::BITCAST) {
21535     SDValue BC0 = N0.getOperand(0);
21536     EVT SVT = BC0.getValueType();
21537     unsigned Opcode = BC0.getOpcode();
21538     unsigned NumElts = VT.getVectorNumElements();
21539
21540     if (BC0.hasOneUse() && SVT.isVector() &&
21541         SVT.getVectorNumElements() * 2 == NumElts &&
21542         TLI.isOperationLegal(Opcode, VT)) {
21543       bool CanFold = false;
21544       switch (Opcode) {
21545       default : break;
21546       case ISD::ADD :
21547       case ISD::FADD :
21548       case ISD::SUB :
21549       case ISD::FSUB :
21550       case ISD::MUL :
21551       case ISD::FMUL :
21552         CanFold = true;
21553       }
21554
21555       unsigned SVTNumElts = SVT.getVectorNumElements();
21556       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21557       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21558         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21559       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21560         CanFold = SVOp->getMaskElt(i) < 0;
21561
21562       if (CanFold) {
21563         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21564         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21565         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21566         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21567       }
21568     }
21569   }
21570
21571   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21572   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21573   // consecutive, non-overlapping, and in the right order.
21574   SmallVector<SDValue, 16> Elts;
21575   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21576     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21577
21578   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21579     return LD;
21580
21581   if (isTargetShuffle(N->getOpcode())) {
21582     SDValue Shuffle =
21583         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21584     if (Shuffle.getNode())
21585       return Shuffle;
21586
21587     // Try recursively combining arbitrary sequences of x86 shuffle
21588     // instructions into higher-order shuffles. We do this after combining
21589     // specific PSHUF instruction sequences into their minimal form so that we
21590     // can evaluate how many specialized shuffle instructions are involved in
21591     // a particular chain.
21592     SmallVector<int, 1> NonceMask; // Just a placeholder.
21593     NonceMask.push_back(0);
21594     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21595                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21596                                       DCI, Subtarget))
21597       return SDValue(); // This routine will use CombineTo to replace N.
21598   }
21599
21600   return SDValue();
21601 }
21602
21603 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21604 /// specific shuffle of a load can be folded into a single element load.
21605 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21606 /// shuffles have been custom lowered so we need to handle those here.
21607 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21608                                          TargetLowering::DAGCombinerInfo &DCI) {
21609   if (DCI.isBeforeLegalizeOps())
21610     return SDValue();
21611
21612   SDValue InVec = N->getOperand(0);
21613   SDValue EltNo = N->getOperand(1);
21614
21615   if (!isa<ConstantSDNode>(EltNo))
21616     return SDValue();
21617
21618   EVT OriginalVT = InVec.getValueType();
21619
21620   if (InVec.getOpcode() == ISD::BITCAST) {
21621     // Don't duplicate a load with other uses.
21622     if (!InVec.hasOneUse())
21623       return SDValue();
21624     EVT BCVT = InVec.getOperand(0).getValueType();
21625     if (!BCVT.isVector() ||
21626         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21627       return SDValue();
21628     InVec = InVec.getOperand(0);
21629   }
21630
21631   EVT CurrentVT = InVec.getValueType();
21632
21633   if (!isTargetShuffle(InVec.getOpcode()))
21634     return SDValue();
21635
21636   // Don't duplicate a load with other uses.
21637   if (!InVec.hasOneUse())
21638     return SDValue();
21639
21640   SmallVector<int, 16> ShuffleMask;
21641   bool UnaryShuffle;
21642   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21643                             ShuffleMask, UnaryShuffle))
21644     return SDValue();
21645
21646   // Select the input vector, guarding against out of range extract vector.
21647   unsigned NumElems = CurrentVT.getVectorNumElements();
21648   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21649   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21650   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21651                                          : InVec.getOperand(1);
21652
21653   // If inputs to shuffle are the same for both ops, then allow 2 uses
21654   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21655                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21656
21657   if (LdNode.getOpcode() == ISD::BITCAST) {
21658     // Don't duplicate a load with other uses.
21659     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21660       return SDValue();
21661
21662     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21663     LdNode = LdNode.getOperand(0);
21664   }
21665
21666   if (!ISD::isNormalLoad(LdNode.getNode()))
21667     return SDValue();
21668
21669   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21670
21671   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21672     return SDValue();
21673
21674   EVT EltVT = N->getValueType(0);
21675   // If there's a bitcast before the shuffle, check if the load type and
21676   // alignment is valid.
21677   unsigned Align = LN0->getAlignment();
21678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21679   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
21680       EltVT.getTypeForEVT(*DAG.getContext()));
21681
21682   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21683     return SDValue();
21684
21685   // All checks match so transform back to vector_shuffle so that DAG combiner
21686   // can finish the job
21687   SDLoc dl(N);
21688
21689   // Create shuffle node taking into account the case that its a unary shuffle
21690   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21691                                    : InVec.getOperand(1);
21692   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21693                                  InVec.getOperand(0), Shuffle,
21694                                  &ShuffleMask[0]);
21695   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21696   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21697                      EltNo);
21698 }
21699
21700 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21701 /// special and don't usually play with other vector types, it's better to
21702 /// handle them early to be sure we emit efficient code by avoiding
21703 /// store-load conversions.
21704 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21705   if (N->getValueType(0) != MVT::x86mmx ||
21706       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21707       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21708     return SDValue();
21709
21710   SDValue V = N->getOperand(0);
21711   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21712   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21713     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21714                        N->getValueType(0), V.getOperand(0));
21715
21716   return SDValue();
21717 }
21718
21719 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21720 /// generation and convert it from being a bunch of shuffles and extracts
21721 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21722 /// storing the value and loading scalars back, while for x64 we should
21723 /// use 64-bit extracts and shifts.
21724 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21725                                          TargetLowering::DAGCombinerInfo &DCI) {
21726   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21727     return NewOp;
21728
21729   SDValue InputVector = N->getOperand(0);
21730   SDLoc dl(InputVector);
21731   // Detect mmx to i32 conversion through a v2i32 elt extract.
21732   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21733       N->getValueType(0) == MVT::i32 &&
21734       InputVector.getValueType() == MVT::v2i32) {
21735
21736     // The bitcast source is a direct mmx result.
21737     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21738     if (MMXSrc.getValueType() == MVT::x86mmx)
21739       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21740                          N->getValueType(0),
21741                          InputVector.getNode()->getOperand(0));
21742
21743     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21744     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21745     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21746         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21747         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21748         MMXSrcOp.getValueType() == MVT::v1i64 &&
21749         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21750       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21751                          N->getValueType(0),
21752                          MMXSrcOp.getOperand(0));
21753   }
21754
21755   EVT VT = N->getValueType(0);
21756
21757   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21758       InputVector.getOpcode() == ISD::BITCAST &&
21759       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21760     uint64_t ExtractedElt =
21761           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21762     uint64_t InputValue =
21763           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21764     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21765     return DAG.getConstant(Res, dl, MVT::i1);
21766   }
21767   // Only operate on vectors of 4 elements, where the alternative shuffling
21768   // gets to be more expensive.
21769   if (InputVector.getValueType() != MVT::v4i32)
21770     return SDValue();
21771
21772   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21773   // single use which is a sign-extend or zero-extend, and all elements are
21774   // used.
21775   SmallVector<SDNode *, 4> Uses;
21776   unsigned ExtractedElements = 0;
21777   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21778        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21779     if (UI.getUse().getResNo() != InputVector.getResNo())
21780       return SDValue();
21781
21782     SDNode *Extract = *UI;
21783     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21784       return SDValue();
21785
21786     if (Extract->getValueType(0) != MVT::i32)
21787       return SDValue();
21788     if (!Extract->hasOneUse())
21789       return SDValue();
21790     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21791         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21792       return SDValue();
21793     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21794       return SDValue();
21795
21796     // Record which element was extracted.
21797     ExtractedElements |=
21798       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21799
21800     Uses.push_back(Extract);
21801   }
21802
21803   // If not all the elements were used, this may not be worthwhile.
21804   if (ExtractedElements != 15)
21805     return SDValue();
21806
21807   // Ok, we've now decided to do the transformation.
21808   // If 64-bit shifts are legal, use the extract-shift sequence,
21809   // otherwise bounce the vector off the cache.
21810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21811   SDValue Vals[4];
21812
21813   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21814     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21815     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21816     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21817       DAG.getConstant(0, dl, VecIdxTy));
21818     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21819       DAG.getConstant(1, dl, VecIdxTy));
21820
21821     SDValue ShAmt = DAG.getConstant(32, dl,
21822       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21823     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21824     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21825       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21826     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21827     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21828       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21829   } else {
21830     // Store the value to a temporary stack slot.
21831     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21832     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21833       MachinePointerInfo(), false, false, 0);
21834
21835     EVT ElementType = InputVector.getValueType().getVectorElementType();
21836     unsigned EltSize = ElementType.getSizeInBits() / 8;
21837
21838     // Replace each use (extract) with a load of the appropriate element.
21839     for (unsigned i = 0; i < 4; ++i) {
21840       uint64_t Offset = EltSize * i;
21841       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21842
21843       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21844                                        StackPtr, OffsetVal);
21845
21846       // Load the scalar.
21847       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21848                             ScalarAddr, MachinePointerInfo(),
21849                             false, false, false, 0);
21850
21851     }
21852   }
21853
21854   // Replace the extracts
21855   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21856     UE = Uses.end(); UI != UE; ++UI) {
21857     SDNode *Extract = *UI;
21858
21859     SDValue Idx = Extract->getOperand(1);
21860     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21861     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21862   }
21863
21864   // The replacement was made in place; don't return anything.
21865   return SDValue();
21866 }
21867
21868 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21869 static std::pair<unsigned, bool>
21870 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21871                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21872   if (!VT.isVector())
21873     return std::make_pair(0, false);
21874
21875   bool NeedSplit = false;
21876   switch (VT.getSimpleVT().SimpleTy) {
21877   default: return std::make_pair(0, false);
21878   case MVT::v4i64:
21879   case MVT::v2i64:
21880     if (!Subtarget->hasVLX())
21881       return std::make_pair(0, false);
21882     break;
21883   case MVT::v64i8:
21884   case MVT::v32i16:
21885     if (!Subtarget->hasBWI())
21886       return std::make_pair(0, false);
21887     break;
21888   case MVT::v16i32:
21889   case MVT::v8i64:
21890     if (!Subtarget->hasAVX512())
21891       return std::make_pair(0, false);
21892     break;
21893   case MVT::v32i8:
21894   case MVT::v16i16:
21895   case MVT::v8i32:
21896     if (!Subtarget->hasAVX2())
21897       NeedSplit = true;
21898     if (!Subtarget->hasAVX())
21899       return std::make_pair(0, false);
21900     break;
21901   case MVT::v16i8:
21902   case MVT::v8i16:
21903   case MVT::v4i32:
21904     if (!Subtarget->hasSSE2())
21905       return std::make_pair(0, false);
21906   }
21907
21908   // SSE2 has only a small subset of the operations.
21909   bool hasUnsigned = Subtarget->hasSSE41() ||
21910                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21911   bool hasSigned = Subtarget->hasSSE41() ||
21912                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21913
21914   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21915
21916   unsigned Opc = 0;
21917   // Check for x CC y ? x : y.
21918   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21919       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21920     switch (CC) {
21921     default: break;
21922     case ISD::SETULT:
21923     case ISD::SETULE:
21924       Opc = hasUnsigned ? ISD::UMIN : 0; break;
21925     case ISD::SETUGT:
21926     case ISD::SETUGE:
21927       Opc = hasUnsigned ? ISD::UMAX : 0; break;
21928     case ISD::SETLT:
21929     case ISD::SETLE:
21930       Opc = hasSigned ? ISD::SMIN : 0; break;
21931     case ISD::SETGT:
21932     case ISD::SETGE:
21933       Opc = hasSigned ? ISD::SMAX : 0; break;
21934     }
21935   // Check for x CC y ? y : x -- a min/max with reversed arms.
21936   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21937              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21938     switch (CC) {
21939     default: break;
21940     case ISD::SETULT:
21941     case ISD::SETULE:
21942       Opc = hasUnsigned ? ISD::UMAX : 0; break;
21943     case ISD::SETUGT:
21944     case ISD::SETUGE:
21945       Opc = hasUnsigned ? ISD::UMIN : 0; break;
21946     case ISD::SETLT:
21947     case ISD::SETLE:
21948       Opc = hasSigned ? ISD::SMAX : 0; break;
21949     case ISD::SETGT:
21950     case ISD::SETGE:
21951       Opc = hasSigned ? ISD::SMIN : 0; break;
21952     }
21953   }
21954
21955   return std::make_pair(Opc, NeedSplit);
21956 }
21957
21958 static SDValue
21959 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21960                                       const X86Subtarget *Subtarget) {
21961   SDLoc dl(N);
21962   SDValue Cond = N->getOperand(0);
21963   SDValue LHS = N->getOperand(1);
21964   SDValue RHS = N->getOperand(2);
21965
21966   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21967     SDValue CondSrc = Cond->getOperand(0);
21968     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21969       Cond = CondSrc->getOperand(0);
21970   }
21971
21972   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21973     return SDValue();
21974
21975   // A vselect where all conditions and data are constants can be optimized into
21976   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21977   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21978       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21979     return SDValue();
21980
21981   unsigned MaskValue = 0;
21982   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21983     return SDValue();
21984
21985   MVT VT = N->getSimpleValueType(0);
21986   unsigned NumElems = VT.getVectorNumElements();
21987   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21988   for (unsigned i = 0; i < NumElems; ++i) {
21989     // Be sure we emit undef where we can.
21990     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21991       ShuffleMask[i] = -1;
21992     else
21993       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21994   }
21995
21996   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21997   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21998     return SDValue();
21999   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22000 }
22001
22002 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22003 /// nodes.
22004 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22005                                     TargetLowering::DAGCombinerInfo &DCI,
22006                                     const X86Subtarget *Subtarget) {
22007   SDLoc DL(N);
22008   SDValue Cond = N->getOperand(0);
22009   // Get the LHS/RHS of the select.
22010   SDValue LHS = N->getOperand(1);
22011   SDValue RHS = N->getOperand(2);
22012   EVT VT = LHS.getValueType();
22013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22014
22015   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22016   // instructions match the semantics of the common C idiom x<y?x:y but not
22017   // x<=y?x:y, because of how they handle negative zero (which can be
22018   // ignored in unsafe-math mode).
22019   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22020   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22021       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22022       (Subtarget->hasSSE2() ||
22023        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22024     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22025
22026     unsigned Opcode = 0;
22027     // Check for x CC y ? x : y.
22028     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22029         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22030       switch (CC) {
22031       default: break;
22032       case ISD::SETULT:
22033         // Converting this to a min would handle NaNs incorrectly, and swapping
22034         // the operands would cause it to handle comparisons between positive
22035         // and negative zero incorrectly.
22036         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22037           if (!DAG.getTarget().Options.UnsafeFPMath &&
22038               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22039             break;
22040           std::swap(LHS, RHS);
22041         }
22042         Opcode = X86ISD::FMIN;
22043         break;
22044       case ISD::SETOLE:
22045         // Converting this to a min would handle comparisons between positive
22046         // and negative zero incorrectly.
22047         if (!DAG.getTarget().Options.UnsafeFPMath &&
22048             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22049           break;
22050         Opcode = X86ISD::FMIN;
22051         break;
22052       case ISD::SETULE:
22053         // Converting this to a min would handle both negative zeros and NaNs
22054         // incorrectly, but we can swap the operands to fix both.
22055         std::swap(LHS, RHS);
22056       case ISD::SETOLT:
22057       case ISD::SETLT:
22058       case ISD::SETLE:
22059         Opcode = X86ISD::FMIN;
22060         break;
22061
22062       case ISD::SETOGE:
22063         // Converting this to a max would handle comparisons between positive
22064         // and negative zero incorrectly.
22065         if (!DAG.getTarget().Options.UnsafeFPMath &&
22066             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22067           break;
22068         Opcode = X86ISD::FMAX;
22069         break;
22070       case ISD::SETUGT:
22071         // Converting this to a max would handle NaNs incorrectly, and swapping
22072         // the operands would cause it to handle comparisons between positive
22073         // and negative zero incorrectly.
22074         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22075           if (!DAG.getTarget().Options.UnsafeFPMath &&
22076               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22077             break;
22078           std::swap(LHS, RHS);
22079         }
22080         Opcode = X86ISD::FMAX;
22081         break;
22082       case ISD::SETUGE:
22083         // Converting this to a max would handle both negative zeros and NaNs
22084         // incorrectly, but we can swap the operands to fix both.
22085         std::swap(LHS, RHS);
22086       case ISD::SETOGT:
22087       case ISD::SETGT:
22088       case ISD::SETGE:
22089         Opcode = X86ISD::FMAX;
22090         break;
22091       }
22092     // Check for x CC y ? y : x -- a min/max with reversed arms.
22093     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22094                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22095       switch (CC) {
22096       default: break;
22097       case ISD::SETOGE:
22098         // Converting this to a min would handle comparisons between positive
22099         // and negative zero incorrectly, and swapping the operands would
22100         // cause it to handle NaNs incorrectly.
22101         if (!DAG.getTarget().Options.UnsafeFPMath &&
22102             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22103           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22104             break;
22105           std::swap(LHS, RHS);
22106         }
22107         Opcode = X86ISD::FMIN;
22108         break;
22109       case ISD::SETUGT:
22110         // Converting this to a min would handle NaNs incorrectly.
22111         if (!DAG.getTarget().Options.UnsafeFPMath &&
22112             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22113           break;
22114         Opcode = X86ISD::FMIN;
22115         break;
22116       case ISD::SETUGE:
22117         // Converting this to a min 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::FMIN;
22124         break;
22125
22126       case ISD::SETULT:
22127         // Converting this to a max would handle NaNs incorrectly.
22128         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22129           break;
22130         Opcode = X86ISD::FMAX;
22131         break;
22132       case ISD::SETOLE:
22133         // Converting this to a max would handle comparisons between positive
22134         // and negative zero incorrectly, and swapping the operands would
22135         // cause it to handle NaNs incorrectly.
22136         if (!DAG.getTarget().Options.UnsafeFPMath &&
22137             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22138           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22139             break;
22140           std::swap(LHS, RHS);
22141         }
22142         Opcode = X86ISD::FMAX;
22143         break;
22144       case ISD::SETULE:
22145         // Converting this to a max would handle both negative zeros and NaNs
22146         // incorrectly, but we can swap the operands to fix both.
22147         std::swap(LHS, RHS);
22148       case ISD::SETOLT:
22149       case ISD::SETLT:
22150       case ISD::SETLE:
22151         Opcode = X86ISD::FMAX;
22152         break;
22153       }
22154     }
22155
22156     if (Opcode)
22157       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22158   }
22159
22160   EVT CondVT = Cond.getValueType();
22161   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22162       CondVT.getVectorElementType() == MVT::i1) {
22163     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22164     // lowering on KNL. In this case we convert it to
22165     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22166     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22167     // Since SKX these selects have a proper lowering.
22168     EVT OpVT = LHS.getValueType();
22169     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22170         (OpVT.getVectorElementType() == MVT::i8 ||
22171          OpVT.getVectorElementType() == MVT::i16) &&
22172         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22173       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22174       DCI.AddToWorklist(Cond.getNode());
22175       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22176     }
22177   }
22178   // If this is a select between two integer constants, try to do some
22179   // optimizations.
22180   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22181     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22182       // Don't do this for crazy integer types.
22183       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22184         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22185         // so that TrueC (the true value) is larger than FalseC.
22186         bool NeedsCondInvert = false;
22187
22188         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22189             // Efficiently invertible.
22190             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22191              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22192               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22193           NeedsCondInvert = true;
22194           std::swap(TrueC, FalseC);
22195         }
22196
22197         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22198         if (FalseC->getAPIntValue() == 0 &&
22199             TrueC->getAPIntValue().isPowerOf2()) {
22200           if (NeedsCondInvert) // Invert the condition if needed.
22201             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22202                                DAG.getConstant(1, DL, Cond.getValueType()));
22203
22204           // Zero extend the condition if needed.
22205           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22206
22207           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22208           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22209                              DAG.getConstant(ShAmt, DL, MVT::i8));
22210         }
22211
22212         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22213         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22214           if (NeedsCondInvert) // Invert the condition if needed.
22215             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22216                                DAG.getConstant(1, DL, Cond.getValueType()));
22217
22218           // Zero extend the condition if needed.
22219           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22220                              FalseC->getValueType(0), Cond);
22221           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22222                              SDValue(FalseC, 0));
22223         }
22224
22225         // Optimize cases that will turn into an LEA instruction.  This requires
22226         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22227         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22228           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22229           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22230
22231           bool isFastMultiplier = false;
22232           if (Diff < 10) {
22233             switch ((unsigned char)Diff) {
22234               default: break;
22235               case 1:  // result = add base, cond
22236               case 2:  // result = lea base(    , cond*2)
22237               case 3:  // result = lea base(cond, cond*2)
22238               case 4:  // result = lea base(    , cond*4)
22239               case 5:  // result = lea base(cond, cond*4)
22240               case 8:  // result = lea base(    , cond*8)
22241               case 9:  // result = lea base(cond, cond*8)
22242                 isFastMultiplier = true;
22243                 break;
22244             }
22245           }
22246
22247           if (isFastMultiplier) {
22248             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22249             if (NeedsCondInvert) // Invert the condition if needed.
22250               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22251                                  DAG.getConstant(1, DL, Cond.getValueType()));
22252
22253             // Zero extend the condition if needed.
22254             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22255                                Cond);
22256             // Scale the condition by the difference.
22257             if (Diff != 1)
22258               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22259                                  DAG.getConstant(Diff, DL,
22260                                                  Cond.getValueType()));
22261
22262             // Add the base if non-zero.
22263             if (FalseC->getAPIntValue() != 0)
22264               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22265                                  SDValue(FalseC, 0));
22266             return Cond;
22267           }
22268         }
22269       }
22270   }
22271
22272   // Canonicalize max and min:
22273   // (x > y) ? x : y -> (x >= y) ? x : y
22274   // (x < y) ? x : y -> (x <= y) ? x : y
22275   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22276   // the need for an extra compare
22277   // against zero. e.g.
22278   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22279   // subl   %esi, %edi
22280   // testl  %edi, %edi
22281   // movl   $0, %eax
22282   // cmovgl %edi, %eax
22283   // =>
22284   // xorl   %eax, %eax
22285   // subl   %esi, $edi
22286   // cmovsl %eax, %edi
22287   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22288       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22289       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22290     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22291     switch (CC) {
22292     default: break;
22293     case ISD::SETLT:
22294     case ISD::SETGT: {
22295       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22296       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22297                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22298       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22299     }
22300     }
22301   }
22302
22303   // Early exit check
22304   if (!TLI.isTypeLegal(VT))
22305     return SDValue();
22306
22307   // Match VSELECTs into subs with unsigned saturation.
22308   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22309       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22310       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22311        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22312     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22313
22314     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22315     // left side invert the predicate to simplify logic below.
22316     SDValue Other;
22317     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22318       Other = RHS;
22319       CC = ISD::getSetCCInverse(CC, true);
22320     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22321       Other = LHS;
22322     }
22323
22324     if (Other.getNode() && Other->getNumOperands() == 2 &&
22325         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22326       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22327       SDValue CondRHS = Cond->getOperand(1);
22328
22329       // Look for a general sub with unsigned saturation first.
22330       // x >= y ? x-y : 0 --> subus x, y
22331       // x >  y ? x-y : 0 --> subus x, y
22332       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22333           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22334         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22335
22336       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22337         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22338           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22339             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22340               // If the RHS is a constant we have to reverse the const
22341               // canonicalization.
22342               // x > C-1 ? x+-C : 0 --> subus x, C
22343               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22344                   CondRHSConst->getAPIntValue() ==
22345                       (-OpRHSConst->getAPIntValue() - 1))
22346                 return DAG.getNode(
22347                     X86ISD::SUBUS, DL, VT, OpLHS,
22348                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22349
22350           // Another special case: If C was a sign bit, the sub has been
22351           // canonicalized into a xor.
22352           // FIXME: Would it be better to use computeKnownBits to determine
22353           //        whether it's safe to decanonicalize the xor?
22354           // x s< 0 ? x^C : 0 --> subus x, C
22355           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22356               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22357               OpRHSConst->getAPIntValue().isSignBit())
22358             // Note that we have to rebuild the RHS constant here to ensure we
22359             // don't rely on particular values of undef lanes.
22360             return DAG.getNode(
22361                 X86ISD::SUBUS, DL, VT, OpLHS,
22362                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22363         }
22364     }
22365   }
22366
22367   // Try to match a min/max vector operation.
22368   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22369     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22370     unsigned Opc = ret.first;
22371     bool NeedSplit = ret.second;
22372
22373     if (Opc && NeedSplit) {
22374       unsigned NumElems = VT.getVectorNumElements();
22375       // Extract the LHS vectors
22376       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22377       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22378
22379       // Extract the RHS vectors
22380       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22381       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22382
22383       // Create min/max for each subvector
22384       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22385       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22386
22387       // Merge the result
22388       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22389     } else if (Opc)
22390       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22391   }
22392
22393   // Simplify vector selection if condition value type matches vselect
22394   // operand type
22395   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22396     assert(Cond.getValueType().isVector() &&
22397            "vector select expects a vector selector!");
22398
22399     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22400     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22401
22402     // Try invert the condition if true value is not all 1s and false value
22403     // is not all 0s.
22404     if (!TValIsAllOnes && !FValIsAllZeros &&
22405         // Check if the selector will be produced by CMPP*/PCMP*
22406         Cond.getOpcode() == ISD::SETCC &&
22407         // Check if SETCC has already been promoted
22408         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
22409       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22410       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22411
22412       if (TValIsAllZeros || FValIsAllOnes) {
22413         SDValue CC = Cond.getOperand(2);
22414         ISD::CondCode NewCC =
22415           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22416                                Cond.getOperand(0).getValueType().isInteger());
22417         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22418         std::swap(LHS, RHS);
22419         TValIsAllOnes = FValIsAllOnes;
22420         FValIsAllZeros = TValIsAllZeros;
22421       }
22422     }
22423
22424     if (TValIsAllOnes || FValIsAllZeros) {
22425       SDValue Ret;
22426
22427       if (TValIsAllOnes && FValIsAllZeros)
22428         Ret = Cond;
22429       else if (TValIsAllOnes)
22430         Ret =
22431             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22432       else if (FValIsAllZeros)
22433         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22434                           DAG.getBitcast(CondVT, LHS));
22435
22436       return DAG.getBitcast(VT, Ret);
22437     }
22438   }
22439
22440   // We should generate an X86ISD::BLENDI from a vselect if its argument
22441   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22442   // constants. This specific pattern gets generated when we split a
22443   // selector for a 512 bit vector in a machine without AVX512 (but with
22444   // 256-bit vectors), during legalization:
22445   //
22446   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22447   //
22448   // Iff we find this pattern and the build_vectors are built from
22449   // constants, we translate the vselect into a shuffle_vector that we
22450   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22451   if ((N->getOpcode() == ISD::VSELECT ||
22452        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22453       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22454     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22455     if (Shuffle.getNode())
22456       return Shuffle;
22457   }
22458
22459   // If this is a *dynamic* select (non-constant condition) and we can match
22460   // this node with one of the variable blend instructions, restructure the
22461   // condition so that the blends can use the high bit of each element and use
22462   // SimplifyDemandedBits to simplify the condition operand.
22463   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22464       !DCI.isBeforeLegalize() &&
22465       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22466     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22467
22468     // Don't optimize vector selects that map to mask-registers.
22469     if (BitWidth == 1)
22470       return SDValue();
22471
22472     // We can only handle the cases where VSELECT is directly legal on the
22473     // subtarget. We custom lower VSELECT nodes with constant conditions and
22474     // this makes it hard to see whether a dynamic VSELECT will correctly
22475     // lower, so we both check the operation's status and explicitly handle the
22476     // cases where a *dynamic* blend will fail even though a constant-condition
22477     // blend could be custom lowered.
22478     // FIXME: We should find a better way to handle this class of problems.
22479     // Potentially, we should combine constant-condition vselect nodes
22480     // pre-legalization into shuffles and not mark as many types as custom
22481     // lowered.
22482     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22483       return SDValue();
22484     // FIXME: We don't support i16-element blends currently. We could and
22485     // should support them by making *all* the bits in the condition be set
22486     // rather than just the high bit and using an i8-element blend.
22487     if (VT.getScalarType() == MVT::i16)
22488       return SDValue();
22489     // Dynamic blending was only available from SSE4.1 onward.
22490     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22491       return SDValue();
22492     // Byte blends are only available in AVX2
22493     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22494         !Subtarget->hasAVX2())
22495       return SDValue();
22496
22497     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22498     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22499
22500     APInt KnownZero, KnownOne;
22501     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22502                                           DCI.isBeforeLegalizeOps());
22503     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22504         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22505                                  TLO)) {
22506       // If we changed the computation somewhere in the DAG, this change
22507       // will affect all users of Cond.
22508       // Make sure it is fine and update all the nodes so that we do not
22509       // use the generic VSELECT anymore. Otherwise, we may perform
22510       // wrong optimizations as we messed up with the actual expectation
22511       // for the vector boolean values.
22512       if (Cond != TLO.Old) {
22513         // Check all uses of that condition operand to check whether it will be
22514         // consumed by non-BLEND instructions, which may depend on all bits are
22515         // set properly.
22516         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22517              I != E; ++I)
22518           if (I->getOpcode() != ISD::VSELECT)
22519             // TODO: Add other opcodes eventually lowered into BLEND.
22520             return SDValue();
22521
22522         // Update all the users of the condition, before committing the change,
22523         // so that the VSELECT optimizations that expect the correct vector
22524         // boolean value will not be triggered.
22525         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22526              I != E; ++I)
22527           DAG.ReplaceAllUsesOfValueWith(
22528               SDValue(*I, 0),
22529               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22530                           Cond, I->getOperand(1), I->getOperand(2)));
22531         DCI.CommitTargetLoweringOpt(TLO);
22532         return SDValue();
22533       }
22534       // At this point, only Cond is changed. Change the condition
22535       // just for N to keep the opportunity to optimize all other
22536       // users their own way.
22537       DAG.ReplaceAllUsesOfValueWith(
22538           SDValue(N, 0),
22539           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22540                       TLO.New, N->getOperand(1), N->getOperand(2)));
22541       return SDValue();
22542     }
22543   }
22544
22545   return SDValue();
22546 }
22547
22548 // Check whether a boolean test is testing a boolean value generated by
22549 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22550 // code.
22551 //
22552 // Simplify the following patterns:
22553 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22554 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22555 // to (Op EFLAGS Cond)
22556 //
22557 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22558 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22559 // to (Op EFLAGS !Cond)
22560 //
22561 // where Op could be BRCOND or CMOV.
22562 //
22563 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22564   // Quit if not CMP and SUB with its value result used.
22565   if (Cmp.getOpcode() != X86ISD::CMP &&
22566       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22567       return SDValue();
22568
22569   // Quit if not used as a boolean value.
22570   if (CC != X86::COND_E && CC != X86::COND_NE)
22571     return SDValue();
22572
22573   // Check CMP operands. One of them should be 0 or 1 and the other should be
22574   // an SetCC or extended from it.
22575   SDValue Op1 = Cmp.getOperand(0);
22576   SDValue Op2 = Cmp.getOperand(1);
22577
22578   SDValue SetCC;
22579   const ConstantSDNode* C = nullptr;
22580   bool needOppositeCond = (CC == X86::COND_E);
22581   bool checkAgainstTrue = false; // Is it a comparison against 1?
22582
22583   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22584     SetCC = Op2;
22585   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22586     SetCC = Op1;
22587   else // Quit if all operands are not constants.
22588     return SDValue();
22589
22590   if (C->getZExtValue() == 1) {
22591     needOppositeCond = !needOppositeCond;
22592     checkAgainstTrue = true;
22593   } else if (C->getZExtValue() != 0)
22594     // Quit if the constant is neither 0 or 1.
22595     return SDValue();
22596
22597   bool truncatedToBoolWithAnd = false;
22598   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22599   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22600          SetCC.getOpcode() == ISD::TRUNCATE ||
22601          SetCC.getOpcode() == ISD::AND) {
22602     if (SetCC.getOpcode() == ISD::AND) {
22603       int OpIdx = -1;
22604       ConstantSDNode *CS;
22605       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22606           CS->getZExtValue() == 1)
22607         OpIdx = 1;
22608       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22609           CS->getZExtValue() == 1)
22610         OpIdx = 0;
22611       if (OpIdx == -1)
22612         break;
22613       SetCC = SetCC.getOperand(OpIdx);
22614       truncatedToBoolWithAnd = true;
22615     } else
22616       SetCC = SetCC.getOperand(0);
22617   }
22618
22619   switch (SetCC.getOpcode()) {
22620   case X86ISD::SETCC_CARRY:
22621     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22622     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22623     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22624     // truncated to i1 using 'and'.
22625     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22626       break;
22627     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22628            "Invalid use of SETCC_CARRY!");
22629     // FALL THROUGH
22630   case X86ISD::SETCC:
22631     // Set the condition code or opposite one if necessary.
22632     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22633     if (needOppositeCond)
22634       CC = X86::GetOppositeBranchCondition(CC);
22635     return SetCC.getOperand(1);
22636   case X86ISD::CMOV: {
22637     // Check whether false/true value has canonical one, i.e. 0 or 1.
22638     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22639     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22640     // Quit if true value is not a constant.
22641     if (!TVal)
22642       return SDValue();
22643     // Quit if false value is not a constant.
22644     if (!FVal) {
22645       SDValue Op = SetCC.getOperand(0);
22646       // Skip 'zext' or 'trunc' node.
22647       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22648           Op.getOpcode() == ISD::TRUNCATE)
22649         Op = Op.getOperand(0);
22650       // A special case for rdrand/rdseed, where 0 is set if false cond is
22651       // found.
22652       if ((Op.getOpcode() != X86ISD::RDRAND &&
22653            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22654         return SDValue();
22655     }
22656     // Quit if false value is not the constant 0 or 1.
22657     bool FValIsFalse = true;
22658     if (FVal && FVal->getZExtValue() != 0) {
22659       if (FVal->getZExtValue() != 1)
22660         return SDValue();
22661       // If FVal is 1, opposite cond is needed.
22662       needOppositeCond = !needOppositeCond;
22663       FValIsFalse = false;
22664     }
22665     // Quit if TVal is not the constant opposite of FVal.
22666     if (FValIsFalse && TVal->getZExtValue() != 1)
22667       return SDValue();
22668     if (!FValIsFalse && TVal->getZExtValue() != 0)
22669       return SDValue();
22670     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22671     if (needOppositeCond)
22672       CC = X86::GetOppositeBranchCondition(CC);
22673     return SetCC.getOperand(3);
22674   }
22675   }
22676
22677   return SDValue();
22678 }
22679
22680 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22681 /// Match:
22682 ///   (X86or (X86setcc) (X86setcc))
22683 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22684 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22685                                            X86::CondCode &CC1, SDValue &Flags,
22686                                            bool &isAnd) {
22687   if (Cond->getOpcode() == X86ISD::CMP) {
22688     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22689     if (!CondOp1C || !CondOp1C->isNullValue())
22690       return false;
22691
22692     Cond = Cond->getOperand(0);
22693   }
22694
22695   isAnd = false;
22696
22697   SDValue SetCC0, SetCC1;
22698   switch (Cond->getOpcode()) {
22699   default: return false;
22700   case ISD::AND:
22701   case X86ISD::AND:
22702     isAnd = true;
22703     // fallthru
22704   case ISD::OR:
22705   case X86ISD::OR:
22706     SetCC0 = Cond->getOperand(0);
22707     SetCC1 = Cond->getOperand(1);
22708     break;
22709   };
22710
22711   // Make sure we have SETCC nodes, using the same flags value.
22712   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22713       SetCC1.getOpcode() != X86ISD::SETCC ||
22714       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22715     return false;
22716
22717   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22718   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22719   Flags = SetCC0->getOperand(1);
22720   return true;
22721 }
22722
22723 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22724 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22725                                   TargetLowering::DAGCombinerInfo &DCI,
22726                                   const X86Subtarget *Subtarget) {
22727   SDLoc DL(N);
22728
22729   // If the flag operand isn't dead, don't touch this CMOV.
22730   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22731     return SDValue();
22732
22733   SDValue FalseOp = N->getOperand(0);
22734   SDValue TrueOp = N->getOperand(1);
22735   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22736   SDValue Cond = N->getOperand(3);
22737
22738   if (CC == X86::COND_E || CC == X86::COND_NE) {
22739     switch (Cond.getOpcode()) {
22740     default: break;
22741     case X86ISD::BSR:
22742     case X86ISD::BSF:
22743       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22744       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22745         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22746     }
22747   }
22748
22749   SDValue Flags;
22750
22751   Flags = checkBoolTestSetCCCombine(Cond, CC);
22752   if (Flags.getNode() &&
22753       // Extra check as FCMOV only supports a subset of X86 cond.
22754       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22755     SDValue Ops[] = { FalseOp, TrueOp,
22756                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22757     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22758   }
22759
22760   // If this is a select between two integer constants, try to do some
22761   // optimizations.  Note that the operands are ordered the opposite of SELECT
22762   // operands.
22763   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22764     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22765       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22766       // larger than FalseC (the false value).
22767       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22768         CC = X86::GetOppositeBranchCondition(CC);
22769         std::swap(TrueC, FalseC);
22770         std::swap(TrueOp, FalseOp);
22771       }
22772
22773       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22774       // This is efficient for any integer data type (including i8/i16) and
22775       // shift amount.
22776       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22777         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22778                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22779
22780         // Zero extend the condition if needed.
22781         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22782
22783         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22784         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22785                            DAG.getConstant(ShAmt, DL, MVT::i8));
22786         if (N->getNumValues() == 2)  // Dead flag value?
22787           return DCI.CombineTo(N, Cond, SDValue());
22788         return Cond;
22789       }
22790
22791       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22792       // for any integer data type, including i8/i16.
22793       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22794         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22795                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22796
22797         // Zero extend the condition if needed.
22798         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22799                            FalseC->getValueType(0), Cond);
22800         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22801                            SDValue(FalseC, 0));
22802
22803         if (N->getNumValues() == 2)  // Dead flag value?
22804           return DCI.CombineTo(N, Cond, SDValue());
22805         return Cond;
22806       }
22807
22808       // Optimize cases that will turn into an LEA instruction.  This requires
22809       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22810       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22811         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22812         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22813
22814         bool isFastMultiplier = false;
22815         if (Diff < 10) {
22816           switch ((unsigned char)Diff) {
22817           default: break;
22818           case 1:  // result = add base, cond
22819           case 2:  // result = lea base(    , cond*2)
22820           case 3:  // result = lea base(cond, cond*2)
22821           case 4:  // result = lea base(    , cond*4)
22822           case 5:  // result = lea base(cond, cond*4)
22823           case 8:  // result = lea base(    , cond*8)
22824           case 9:  // result = lea base(cond, cond*8)
22825             isFastMultiplier = true;
22826             break;
22827           }
22828         }
22829
22830         if (isFastMultiplier) {
22831           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22832           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22833                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22834           // Zero extend the condition if needed.
22835           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22836                              Cond);
22837           // Scale the condition by the difference.
22838           if (Diff != 1)
22839             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22840                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22841
22842           // Add the base if non-zero.
22843           if (FalseC->getAPIntValue() != 0)
22844             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22845                                SDValue(FalseC, 0));
22846           if (N->getNumValues() == 2)  // Dead flag value?
22847             return DCI.CombineTo(N, Cond, SDValue());
22848           return Cond;
22849         }
22850       }
22851     }
22852   }
22853
22854   // Handle these cases:
22855   //   (select (x != c), e, c) -> select (x != c), e, x),
22856   //   (select (x == c), c, e) -> select (x == c), x, e)
22857   // where the c is an integer constant, and the "select" is the combination
22858   // of CMOV and CMP.
22859   //
22860   // The rationale for this change is that the conditional-move from a constant
22861   // needs two instructions, however, conditional-move from a register needs
22862   // only one instruction.
22863   //
22864   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22865   //  some instruction-combining opportunities. This opt needs to be
22866   //  postponed as late as possible.
22867   //
22868   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22869     // the DCI.xxxx conditions are provided to postpone the optimization as
22870     // late as possible.
22871
22872     ConstantSDNode *CmpAgainst = nullptr;
22873     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22874         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22875         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22876
22877       if (CC == X86::COND_NE &&
22878           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22879         CC = X86::GetOppositeBranchCondition(CC);
22880         std::swap(TrueOp, FalseOp);
22881       }
22882
22883       if (CC == X86::COND_E &&
22884           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22885         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22886                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22887         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22888       }
22889     }
22890   }
22891
22892   // Fold and/or of setcc's to double CMOV:
22893   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22894   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22895   //
22896   // This combine lets us generate:
22897   //   cmovcc1 (jcc1 if we don't have CMOV)
22898   //   cmovcc2 (same)
22899   // instead of:
22900   //   setcc1
22901   //   setcc2
22902   //   and/or
22903   //   cmovne (jne if we don't have CMOV)
22904   // When we can't use the CMOV instruction, it might increase branch
22905   // mispredicts.
22906   // When we can use CMOV, or when there is no mispredict, this improves
22907   // throughput and reduces register pressure.
22908   //
22909   if (CC == X86::COND_NE) {
22910     SDValue Flags;
22911     X86::CondCode CC0, CC1;
22912     bool isAndSetCC;
22913     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22914       if (isAndSetCC) {
22915         std::swap(FalseOp, TrueOp);
22916         CC0 = X86::GetOppositeBranchCondition(CC0);
22917         CC1 = X86::GetOppositeBranchCondition(CC1);
22918       }
22919
22920       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22921         Flags};
22922       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22923       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22924       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22925       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22926       return CMOV;
22927     }
22928   }
22929
22930   return SDValue();
22931 }
22932
22933 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22934                                                 const X86Subtarget *Subtarget) {
22935   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22936   switch (IntNo) {
22937   default: return SDValue();
22938   // SSE/AVX/AVX2 blend intrinsics.
22939   case Intrinsic::x86_avx2_pblendvb:
22940     // Don't try to simplify this intrinsic if we don't have AVX2.
22941     if (!Subtarget->hasAVX2())
22942       return SDValue();
22943     // FALL-THROUGH
22944   case Intrinsic::x86_avx_blendv_pd_256:
22945   case Intrinsic::x86_avx_blendv_ps_256:
22946     // Don't try to simplify this intrinsic if we don't have AVX.
22947     if (!Subtarget->hasAVX())
22948       return SDValue();
22949     // FALL-THROUGH
22950   case Intrinsic::x86_sse41_blendvps:
22951   case Intrinsic::x86_sse41_blendvpd:
22952   case Intrinsic::x86_sse41_pblendvb: {
22953     SDValue Op0 = N->getOperand(1);
22954     SDValue Op1 = N->getOperand(2);
22955     SDValue Mask = N->getOperand(3);
22956
22957     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22958     if (!Subtarget->hasSSE41())
22959       return SDValue();
22960
22961     // fold (blend A, A, Mask) -> A
22962     if (Op0 == Op1)
22963       return Op0;
22964     // fold (blend A, B, allZeros) -> A
22965     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22966       return Op0;
22967     // fold (blend A, B, allOnes) -> B
22968     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22969       return Op1;
22970
22971     // Simplify the case where the mask is a constant i32 value.
22972     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22973       if (C->isNullValue())
22974         return Op0;
22975       if (C->isAllOnesValue())
22976         return Op1;
22977     }
22978
22979     return SDValue();
22980   }
22981
22982   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22983   case Intrinsic::x86_sse2_psrai_w:
22984   case Intrinsic::x86_sse2_psrai_d:
22985   case Intrinsic::x86_avx2_psrai_w:
22986   case Intrinsic::x86_avx2_psrai_d:
22987   case Intrinsic::x86_sse2_psra_w:
22988   case Intrinsic::x86_sse2_psra_d:
22989   case Intrinsic::x86_avx2_psra_w:
22990   case Intrinsic::x86_avx2_psra_d: {
22991     SDValue Op0 = N->getOperand(1);
22992     SDValue Op1 = N->getOperand(2);
22993     EVT VT = Op0.getValueType();
22994     assert(VT.isVector() && "Expected a vector type!");
22995
22996     if (isa<BuildVectorSDNode>(Op1))
22997       Op1 = Op1.getOperand(0);
22998
22999     if (!isa<ConstantSDNode>(Op1))
23000       return SDValue();
23001
23002     EVT SVT = VT.getVectorElementType();
23003     unsigned SVTBits = SVT.getSizeInBits();
23004
23005     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23006     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23007     uint64_t ShAmt = C.getZExtValue();
23008
23009     // Don't try to convert this shift into a ISD::SRA if the shift
23010     // count is bigger than or equal to the element size.
23011     if (ShAmt >= SVTBits)
23012       return SDValue();
23013
23014     // Trivial case: if the shift count is zero, then fold this
23015     // into the first operand.
23016     if (ShAmt == 0)
23017       return Op0;
23018
23019     // Replace this packed shift intrinsic with a target independent
23020     // shift dag node.
23021     SDLoc DL(N);
23022     SDValue Splat = DAG.getConstant(C, DL, VT);
23023     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23024   }
23025   }
23026 }
23027
23028 /// PerformMulCombine - Optimize a single multiply with constant into two
23029 /// in order to implement it with two cheaper instructions, e.g.
23030 /// LEA + SHL, LEA + LEA.
23031 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23032                                  TargetLowering::DAGCombinerInfo &DCI) {
23033   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23034     return SDValue();
23035
23036   EVT VT = N->getValueType(0);
23037   if (VT != MVT::i64 && VT != MVT::i32)
23038     return SDValue();
23039
23040   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23041   if (!C)
23042     return SDValue();
23043   uint64_t MulAmt = C->getZExtValue();
23044   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23045     return SDValue();
23046
23047   uint64_t MulAmt1 = 0;
23048   uint64_t MulAmt2 = 0;
23049   if ((MulAmt % 9) == 0) {
23050     MulAmt1 = 9;
23051     MulAmt2 = MulAmt / 9;
23052   } else if ((MulAmt % 5) == 0) {
23053     MulAmt1 = 5;
23054     MulAmt2 = MulAmt / 5;
23055   } else if ((MulAmt % 3) == 0) {
23056     MulAmt1 = 3;
23057     MulAmt2 = MulAmt / 3;
23058   }
23059   if (MulAmt2 &&
23060       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23061     SDLoc DL(N);
23062
23063     if (isPowerOf2_64(MulAmt2) &&
23064         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23065       // If second multiplifer is pow2, issue it first. We want the multiply by
23066       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23067       // is an add.
23068       std::swap(MulAmt1, MulAmt2);
23069
23070     SDValue NewMul;
23071     if (isPowerOf2_64(MulAmt1))
23072       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23073                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23074     else
23075       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23076                            DAG.getConstant(MulAmt1, DL, VT));
23077
23078     if (isPowerOf2_64(MulAmt2))
23079       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23080                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23081     else
23082       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23083                            DAG.getConstant(MulAmt2, DL, VT));
23084
23085     // Do not add new nodes to DAG combiner worklist.
23086     DCI.CombineTo(N, NewMul, false);
23087   }
23088   return SDValue();
23089 }
23090
23091 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23092   SDValue N0 = N->getOperand(0);
23093   SDValue N1 = N->getOperand(1);
23094   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23095   EVT VT = N0.getValueType();
23096
23097   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23098   // since the result of setcc_c is all zero's or all ones.
23099   if (VT.isInteger() && !VT.isVector() &&
23100       N1C && N0.getOpcode() == ISD::AND &&
23101       N0.getOperand(1).getOpcode() == ISD::Constant) {
23102     SDValue N00 = N0.getOperand(0);
23103     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23104         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23105           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23106          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23107       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23108       APInt ShAmt = N1C->getAPIntValue();
23109       Mask = Mask.shl(ShAmt);
23110       if (Mask != 0) {
23111         SDLoc DL(N);
23112         return DAG.getNode(ISD::AND, DL, VT,
23113                            N00, DAG.getConstant(Mask, DL, VT));
23114       }
23115     }
23116   }
23117
23118   // Hardware support for vector shifts is sparse which makes us scalarize the
23119   // vector operations in many cases. Also, on sandybridge ADD is faster than
23120   // shl.
23121   // (shl V, 1) -> add V,V
23122   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23123     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23124       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23125       // We shift all of the values by one. In many cases we do not have
23126       // hardware support for this operation. This is better expressed as an ADD
23127       // of two values.
23128       if (N1SplatC->getZExtValue() == 1)
23129         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23130     }
23131
23132   return SDValue();
23133 }
23134
23135 /// \brief Returns a vector of 0s if the node in input is a vector logical
23136 /// shift by a constant amount which is known to be bigger than or equal
23137 /// to the vector element size in bits.
23138 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23139                                       const X86Subtarget *Subtarget) {
23140   EVT VT = N->getValueType(0);
23141
23142   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23143       (!Subtarget->hasInt256() ||
23144        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23145     return SDValue();
23146
23147   SDValue Amt = N->getOperand(1);
23148   SDLoc DL(N);
23149   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23150     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23151       APInt ShiftAmt = AmtSplat->getAPIntValue();
23152       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23153
23154       // SSE2/AVX2 logical shifts always return a vector of 0s
23155       // if the shift amount is bigger than or equal to
23156       // the element size. The constant shift amount will be
23157       // encoded as a 8-bit immediate.
23158       if (ShiftAmt.trunc(8).uge(MaxAmount))
23159         return getZeroVector(VT, Subtarget, DAG, DL);
23160     }
23161
23162   return SDValue();
23163 }
23164
23165 /// PerformShiftCombine - Combine shifts.
23166 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23167                                    TargetLowering::DAGCombinerInfo &DCI,
23168                                    const X86Subtarget *Subtarget) {
23169   if (N->getOpcode() == ISD::SHL)
23170     if (SDValue V = PerformSHLCombine(N, DAG))
23171       return V;
23172
23173   // Try to fold this logical shift into a zero vector.
23174   if (N->getOpcode() != ISD::SRA)
23175     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23176       return V;
23177
23178   return SDValue();
23179 }
23180
23181 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23182 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23183 // and friends.  Likewise for OR -> CMPNEQSS.
23184 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23185                             TargetLowering::DAGCombinerInfo &DCI,
23186                             const X86Subtarget *Subtarget) {
23187   unsigned opcode;
23188
23189   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23190   // we're requiring SSE2 for both.
23191   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23192     SDValue N0 = N->getOperand(0);
23193     SDValue N1 = N->getOperand(1);
23194     SDValue CMP0 = N0->getOperand(1);
23195     SDValue CMP1 = N1->getOperand(1);
23196     SDLoc DL(N);
23197
23198     // The SETCCs should both refer to the same CMP.
23199     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23200       return SDValue();
23201
23202     SDValue CMP00 = CMP0->getOperand(0);
23203     SDValue CMP01 = CMP0->getOperand(1);
23204     EVT     VT    = CMP00.getValueType();
23205
23206     if (VT == MVT::f32 || VT == MVT::f64) {
23207       bool ExpectingFlags = false;
23208       // Check for any users that want flags:
23209       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23210            !ExpectingFlags && UI != UE; ++UI)
23211         switch (UI->getOpcode()) {
23212         default:
23213         case ISD::BR_CC:
23214         case ISD::BRCOND:
23215         case ISD::SELECT:
23216           ExpectingFlags = true;
23217           break;
23218         case ISD::CopyToReg:
23219         case ISD::SIGN_EXTEND:
23220         case ISD::ZERO_EXTEND:
23221         case ISD::ANY_EXTEND:
23222           break;
23223         }
23224
23225       if (!ExpectingFlags) {
23226         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23227         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23228
23229         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23230           X86::CondCode tmp = cc0;
23231           cc0 = cc1;
23232           cc1 = tmp;
23233         }
23234
23235         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23236             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23237           // FIXME: need symbolic constants for these magic numbers.
23238           // See X86ATTInstPrinter.cpp:printSSECC().
23239           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23240           if (Subtarget->hasAVX512()) {
23241             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23242                                          CMP01,
23243                                          DAG.getConstant(x86cc, DL, MVT::i8));
23244             if (N->getValueType(0) != MVT::i1)
23245               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23246                                  FSetCC);
23247             return FSetCC;
23248           }
23249           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23250                                               CMP00.getValueType(), CMP00, CMP01,
23251                                               DAG.getConstant(x86cc, DL,
23252                                                               MVT::i8));
23253
23254           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23255           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23256
23257           if (is64BitFP && !Subtarget->is64Bit()) {
23258             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23259             // 64-bit integer, since that's not a legal type. Since
23260             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23261             // bits, but can do this little dance to extract the lowest 32 bits
23262             // and work with those going forward.
23263             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23264                                            OnesOrZeroesF);
23265             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23266             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23267                                         Vector32, DAG.getIntPtrConstant(0, DL));
23268             IntVT = MVT::i32;
23269           }
23270
23271           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23272           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23273                                       DAG.getConstant(1, DL, IntVT));
23274           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23275                                               ANDed);
23276           return OneBitOfTruth;
23277         }
23278       }
23279     }
23280   }
23281   return SDValue();
23282 }
23283
23284 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23285 /// so it can be folded inside ANDNP.
23286 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23287   EVT VT = N->getValueType(0);
23288
23289   // Match direct AllOnes for 128 and 256-bit vectors
23290   if (ISD::isBuildVectorAllOnes(N))
23291     return true;
23292
23293   // Look through a bit convert.
23294   if (N->getOpcode() == ISD::BITCAST)
23295     N = N->getOperand(0).getNode();
23296
23297   // Sometimes the operand may come from a insert_subvector building a 256-bit
23298   // allones vector
23299   if (VT.is256BitVector() &&
23300       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23301     SDValue V1 = N->getOperand(0);
23302     SDValue V2 = N->getOperand(1);
23303
23304     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23305         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23306         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23307         ISD::isBuildVectorAllOnes(V2.getNode()))
23308       return true;
23309   }
23310
23311   return false;
23312 }
23313
23314 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23315 // register. In most cases we actually compare or select YMM-sized registers
23316 // and mixing the two types creates horrible code. This method optimizes
23317 // some of the transition sequences.
23318 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23319                                  TargetLowering::DAGCombinerInfo &DCI,
23320                                  const X86Subtarget *Subtarget) {
23321   EVT VT = N->getValueType(0);
23322   if (!VT.is256BitVector())
23323     return SDValue();
23324
23325   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23326           N->getOpcode() == ISD::ZERO_EXTEND ||
23327           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23328
23329   SDValue Narrow = N->getOperand(0);
23330   EVT NarrowVT = Narrow->getValueType(0);
23331   if (!NarrowVT.is128BitVector())
23332     return SDValue();
23333
23334   if (Narrow->getOpcode() != ISD::XOR &&
23335       Narrow->getOpcode() != ISD::AND &&
23336       Narrow->getOpcode() != ISD::OR)
23337     return SDValue();
23338
23339   SDValue N0  = Narrow->getOperand(0);
23340   SDValue N1  = Narrow->getOperand(1);
23341   SDLoc DL(Narrow);
23342
23343   // The Left side has to be a trunc.
23344   if (N0.getOpcode() != ISD::TRUNCATE)
23345     return SDValue();
23346
23347   // The type of the truncated inputs.
23348   EVT WideVT = N0->getOperand(0)->getValueType(0);
23349   if (WideVT != VT)
23350     return SDValue();
23351
23352   // The right side has to be a 'trunc' or a constant vector.
23353   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23354   ConstantSDNode *RHSConstSplat = nullptr;
23355   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23356     RHSConstSplat = RHSBV->getConstantSplatNode();
23357   if (!RHSTrunc && !RHSConstSplat)
23358     return SDValue();
23359
23360   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23361
23362   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23363     return SDValue();
23364
23365   // Set N0 and N1 to hold the inputs to the new wide operation.
23366   N0 = N0->getOperand(0);
23367   if (RHSConstSplat) {
23368     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23369                      SDValue(RHSConstSplat, 0));
23370     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23371     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23372   } else if (RHSTrunc) {
23373     N1 = N1->getOperand(0);
23374   }
23375
23376   // Generate the wide operation.
23377   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23378   unsigned Opcode = N->getOpcode();
23379   switch (Opcode) {
23380   case ISD::ANY_EXTEND:
23381     return Op;
23382   case ISD::ZERO_EXTEND: {
23383     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23384     APInt Mask = APInt::getAllOnesValue(InBits);
23385     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23386     return DAG.getNode(ISD::AND, DL, VT,
23387                        Op, DAG.getConstant(Mask, DL, VT));
23388   }
23389   case ISD::SIGN_EXTEND:
23390     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23391                        Op, DAG.getValueType(NarrowVT));
23392   default:
23393     llvm_unreachable("Unexpected opcode");
23394   }
23395 }
23396
23397 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23398                                  TargetLowering::DAGCombinerInfo &DCI,
23399                                  const X86Subtarget *Subtarget) {
23400   SDValue N0 = N->getOperand(0);
23401   SDValue N1 = N->getOperand(1);
23402   SDLoc DL(N);
23403
23404   // A vector zext_in_reg may be represented as a shuffle,
23405   // feeding into a bitcast (this represents anyext) feeding into
23406   // an and with a mask.
23407   // We'd like to try to combine that into a shuffle with zero
23408   // plus a bitcast, removing the and.
23409   if (N0.getOpcode() != ISD::BITCAST ||
23410       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23411     return SDValue();
23412
23413   // The other side of the AND should be a splat of 2^C, where C
23414   // is the number of bits in the source type.
23415   if (N1.getOpcode() == ISD::BITCAST)
23416     N1 = N1.getOperand(0);
23417   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23418     return SDValue();
23419   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23420
23421   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23422   EVT SrcType = Shuffle->getValueType(0);
23423
23424   // We expect a single-source shuffle
23425   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23426     return SDValue();
23427
23428   unsigned SrcSize = SrcType.getScalarSizeInBits();
23429
23430   APInt SplatValue, SplatUndef;
23431   unsigned SplatBitSize;
23432   bool HasAnyUndefs;
23433   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23434                                 SplatBitSize, HasAnyUndefs))
23435     return SDValue();
23436
23437   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23438   // Make sure the splat matches the mask we expect
23439   if (SplatBitSize > ResSize ||
23440       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23441     return SDValue();
23442
23443   // Make sure the input and output size make sense
23444   if (SrcSize >= ResSize || ResSize % SrcSize)
23445     return SDValue();
23446
23447   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23448   // The number of u's between each two values depends on the ratio between
23449   // the source and dest type.
23450   unsigned ZextRatio = ResSize / SrcSize;
23451   bool IsZext = true;
23452   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23453     if (i % ZextRatio) {
23454       if (Shuffle->getMaskElt(i) > 0) {
23455         // Expected undef
23456         IsZext = false;
23457         break;
23458       }
23459     } else {
23460       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23461         // Expected element number
23462         IsZext = false;
23463         break;
23464       }
23465     }
23466   }
23467
23468   if (!IsZext)
23469     return SDValue();
23470
23471   // Ok, perform the transformation - replace the shuffle with
23472   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23473   // (instead of undef) where the k elements come from the zero vector.
23474   SmallVector<int, 8> Mask;
23475   unsigned NumElems = SrcType.getVectorNumElements();
23476   for (unsigned i = 0; i < NumElems; ++i)
23477     if (i % ZextRatio)
23478       Mask.push_back(NumElems);
23479     else
23480       Mask.push_back(i / ZextRatio);
23481
23482   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23483     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23484   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23485 }
23486
23487 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23488                                  TargetLowering::DAGCombinerInfo &DCI,
23489                                  const X86Subtarget *Subtarget) {
23490   if (DCI.isBeforeLegalizeOps())
23491     return SDValue();
23492
23493   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23494     return Zext;
23495
23496   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23497     return R;
23498
23499   EVT VT = N->getValueType(0);
23500   SDValue N0 = N->getOperand(0);
23501   SDValue N1 = N->getOperand(1);
23502   SDLoc DL(N);
23503
23504   // Create BEXTR instructions
23505   // BEXTR is ((X >> imm) & (2**size-1))
23506   if (VT == MVT::i32 || VT == MVT::i64) {
23507     // Check for BEXTR.
23508     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23509         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23510       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23511       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23512       if (MaskNode && ShiftNode) {
23513         uint64_t Mask = MaskNode->getZExtValue();
23514         uint64_t Shift = ShiftNode->getZExtValue();
23515         if (isMask_64(Mask)) {
23516           uint64_t MaskSize = countPopulation(Mask);
23517           if (Shift + MaskSize <= VT.getSizeInBits())
23518             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23519                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23520                                                VT));
23521         }
23522       }
23523     } // BEXTR
23524
23525     return SDValue();
23526   }
23527
23528   // Want to form ANDNP nodes:
23529   // 1) In the hopes of then easily combining them with OR and AND nodes
23530   //    to form PBLEND/PSIGN.
23531   // 2) To match ANDN packed intrinsics
23532   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23533     return SDValue();
23534
23535   // Check LHS for vnot
23536   if (N0.getOpcode() == ISD::XOR &&
23537       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23538       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23539     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23540
23541   // Check RHS for vnot
23542   if (N1.getOpcode() == ISD::XOR &&
23543       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23544       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23545     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23546
23547   return SDValue();
23548 }
23549
23550 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23551                                 TargetLowering::DAGCombinerInfo &DCI,
23552                                 const X86Subtarget *Subtarget) {
23553   if (DCI.isBeforeLegalizeOps())
23554     return SDValue();
23555
23556   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23557     return R;
23558
23559   SDValue N0 = N->getOperand(0);
23560   SDValue N1 = N->getOperand(1);
23561   EVT VT = N->getValueType(0);
23562
23563   // look for psign/blend
23564   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23565     if (!Subtarget->hasSSSE3() ||
23566         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23567       return SDValue();
23568
23569     // Canonicalize pandn to RHS
23570     if (N0.getOpcode() == X86ISD::ANDNP)
23571       std::swap(N0, N1);
23572     // or (and (m, y), (pandn m, x))
23573     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23574       SDValue Mask = N1.getOperand(0);
23575       SDValue X    = N1.getOperand(1);
23576       SDValue Y;
23577       if (N0.getOperand(0) == Mask)
23578         Y = N0.getOperand(1);
23579       if (N0.getOperand(1) == Mask)
23580         Y = N0.getOperand(0);
23581
23582       // Check to see if the mask appeared in both the AND and ANDNP and
23583       if (!Y.getNode())
23584         return SDValue();
23585
23586       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23587       // Look through mask bitcast.
23588       if (Mask.getOpcode() == ISD::BITCAST)
23589         Mask = Mask.getOperand(0);
23590       if (X.getOpcode() == ISD::BITCAST)
23591         X = X.getOperand(0);
23592       if (Y.getOpcode() == ISD::BITCAST)
23593         Y = Y.getOperand(0);
23594
23595       EVT MaskVT = Mask.getValueType();
23596
23597       // Validate that the Mask operand is a vector sra node.
23598       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23599       // there is no psrai.b
23600       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23601       unsigned SraAmt = ~0;
23602       if (Mask.getOpcode() == ISD::SRA) {
23603         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23604           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23605             SraAmt = AmtConst->getZExtValue();
23606       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23607         SDValue SraC = Mask.getOperand(1);
23608         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23609       }
23610       if ((SraAmt + 1) != EltBits)
23611         return SDValue();
23612
23613       SDLoc DL(N);
23614
23615       // Now we know we at least have a plendvb with the mask val.  See if
23616       // we can form a psignb/w/d.
23617       // psign = x.type == y.type == mask.type && y = sub(0, x);
23618       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23619           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23620           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23621         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23622                "Unsupported VT for PSIGN");
23623         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23624         return DAG.getBitcast(VT, Mask);
23625       }
23626       // PBLENDVB only available on SSE 4.1
23627       if (!Subtarget->hasSSE41())
23628         return SDValue();
23629
23630       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23631
23632       X = DAG.getBitcast(BlendVT, X);
23633       Y = DAG.getBitcast(BlendVT, Y);
23634       Mask = DAG.getBitcast(BlendVT, Mask);
23635       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23636       return DAG.getBitcast(VT, Mask);
23637     }
23638   }
23639
23640   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23641     return SDValue();
23642
23643   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23644   MachineFunction &MF = DAG.getMachineFunction();
23645   bool OptForSize =
23646       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23647
23648   // SHLD/SHRD instructions have lower register pressure, but on some
23649   // platforms they have higher latency than the equivalent
23650   // series of shifts/or that would otherwise be generated.
23651   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23652   // have higher latencies and we are not optimizing for size.
23653   if (!OptForSize && Subtarget->isSHLDSlow())
23654     return SDValue();
23655
23656   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23657     std::swap(N0, N1);
23658   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23659     return SDValue();
23660   if (!N0.hasOneUse() || !N1.hasOneUse())
23661     return SDValue();
23662
23663   SDValue ShAmt0 = N0.getOperand(1);
23664   if (ShAmt0.getValueType() != MVT::i8)
23665     return SDValue();
23666   SDValue ShAmt1 = N1.getOperand(1);
23667   if (ShAmt1.getValueType() != MVT::i8)
23668     return SDValue();
23669   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23670     ShAmt0 = ShAmt0.getOperand(0);
23671   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23672     ShAmt1 = ShAmt1.getOperand(0);
23673
23674   SDLoc DL(N);
23675   unsigned Opc = X86ISD::SHLD;
23676   SDValue Op0 = N0.getOperand(0);
23677   SDValue Op1 = N1.getOperand(0);
23678   if (ShAmt0.getOpcode() == ISD::SUB) {
23679     Opc = X86ISD::SHRD;
23680     std::swap(Op0, Op1);
23681     std::swap(ShAmt0, ShAmt1);
23682   }
23683
23684   unsigned Bits = VT.getSizeInBits();
23685   if (ShAmt1.getOpcode() == ISD::SUB) {
23686     SDValue Sum = ShAmt1.getOperand(0);
23687     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23688       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23689       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23690         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23691       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23692         return DAG.getNode(Opc, DL, VT,
23693                            Op0, Op1,
23694                            DAG.getNode(ISD::TRUNCATE, DL,
23695                                        MVT::i8, ShAmt0));
23696     }
23697   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23698     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23699     if (ShAmt0C &&
23700         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23701       return DAG.getNode(Opc, DL, VT,
23702                          N0.getOperand(0), N1.getOperand(0),
23703                          DAG.getNode(ISD::TRUNCATE, DL,
23704                                        MVT::i8, ShAmt0));
23705   }
23706
23707   return SDValue();
23708 }
23709
23710 // Generate NEG and CMOV for integer abs.
23711 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23712   EVT VT = N->getValueType(0);
23713
23714   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23715   // 8-bit integer abs to NEG and CMOV.
23716   if (VT.isInteger() && VT.getSizeInBits() == 8)
23717     return SDValue();
23718
23719   SDValue N0 = N->getOperand(0);
23720   SDValue N1 = N->getOperand(1);
23721   SDLoc DL(N);
23722
23723   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23724   // and change it to SUB and CMOV.
23725   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23726       N0.getOpcode() == ISD::ADD &&
23727       N0.getOperand(1) == N1 &&
23728       N1.getOpcode() == ISD::SRA &&
23729       N1.getOperand(0) == N0.getOperand(0))
23730     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23731       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23732         // Generate SUB & CMOV.
23733         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23734                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23735
23736         SDValue Ops[] = { N0.getOperand(0), Neg,
23737                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23738                           SDValue(Neg.getNode(), 1) };
23739         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23740       }
23741   return SDValue();
23742 }
23743
23744 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23745 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23746                                  TargetLowering::DAGCombinerInfo &DCI,
23747                                  const X86Subtarget *Subtarget) {
23748   if (DCI.isBeforeLegalizeOps())
23749     return SDValue();
23750
23751   if (Subtarget->hasCMov())
23752     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23753       return RV;
23754
23755   return SDValue();
23756 }
23757
23758 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23759 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23760                                   TargetLowering::DAGCombinerInfo &DCI,
23761                                   const X86Subtarget *Subtarget) {
23762   LoadSDNode *Ld = cast<LoadSDNode>(N);
23763   EVT RegVT = Ld->getValueType(0);
23764   EVT MemVT = Ld->getMemoryVT();
23765   SDLoc dl(Ld);
23766   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23767
23768   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23769   // into two 16-byte operations.
23770   ISD::LoadExtType Ext = Ld->getExtensionType();
23771   unsigned Alignment = Ld->getAlignment();
23772   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23773   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23774       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23775     unsigned NumElems = RegVT.getVectorNumElements();
23776     if (NumElems < 2)
23777       return SDValue();
23778
23779     SDValue Ptr = Ld->getBasePtr();
23780     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23781
23782     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23783                                   NumElems/2);
23784     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23785                                 Ld->getPointerInfo(), Ld->isVolatile(),
23786                                 Ld->isNonTemporal(), Ld->isInvariant(),
23787                                 Alignment);
23788     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23789     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23790                                 Ld->getPointerInfo(), Ld->isVolatile(),
23791                                 Ld->isNonTemporal(), Ld->isInvariant(),
23792                                 std::min(16U, Alignment));
23793     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23794                              Load1.getValue(1),
23795                              Load2.getValue(1));
23796
23797     SDValue NewVec = DAG.getUNDEF(RegVT);
23798     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23799     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23800     return DCI.CombineTo(N, NewVec, TF, true);
23801   }
23802
23803   return SDValue();
23804 }
23805
23806 /// PerformMLOADCombine - Resolve extending loads
23807 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23808                                    TargetLowering::DAGCombinerInfo &DCI,
23809                                    const X86Subtarget *Subtarget) {
23810   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23811   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23812     return SDValue();
23813
23814   EVT VT = Mld->getValueType(0);
23815   unsigned NumElems = VT.getVectorNumElements();
23816   EVT LdVT = Mld->getMemoryVT();
23817   SDLoc dl(Mld);
23818
23819   assert(LdVT != VT && "Cannot extend to the same type");
23820   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23821   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23822   // From, To sizes and ElemCount must be pow of two
23823   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23824     "Unexpected size for extending masked load");
23825
23826   unsigned SizeRatio  = ToSz / FromSz;
23827   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23828
23829   // Create a type on which we perform the shuffle
23830   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23831           LdVT.getScalarType(), NumElems*SizeRatio);
23832   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23833
23834   // Convert Src0 value
23835   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
23836   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23837     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23838     for (unsigned i = 0; i != NumElems; ++i)
23839       ShuffleVec[i] = i * SizeRatio;
23840
23841     // Can't shuffle using an illegal type.
23842     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23843             && "WideVecVT should be legal");
23844     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23845                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23846   }
23847   // Prepare the new mask
23848   SDValue NewMask;
23849   SDValue Mask = Mld->getMask();
23850   if (Mask.getValueType() == VT) {
23851     // Mask and original value have the same type
23852     NewMask = DAG.getBitcast(WideVecVT, Mask);
23853     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23854     for (unsigned i = 0; i != NumElems; ++i)
23855       ShuffleVec[i] = i * SizeRatio;
23856     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23857       ShuffleVec[i] = NumElems*SizeRatio;
23858     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23859                                    DAG.getConstant(0, dl, WideVecVT),
23860                                    &ShuffleVec[0]);
23861   }
23862   else {
23863     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23864     unsigned WidenNumElts = NumElems*SizeRatio;
23865     unsigned MaskNumElts = VT.getVectorNumElements();
23866     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23867                                      WidenNumElts);
23868
23869     unsigned NumConcat = WidenNumElts / MaskNumElts;
23870     SmallVector<SDValue, 16> Ops(NumConcat);
23871     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23872     Ops[0] = Mask;
23873     for (unsigned i = 1; i != NumConcat; ++i)
23874       Ops[i] = ZeroVal;
23875
23876     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23877   }
23878
23879   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23880                                      Mld->getBasePtr(), NewMask, WideSrc0,
23881                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23882                                      ISD::NON_EXTLOAD);
23883   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23884   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23885
23886 }
23887 /// PerformMSTORECombine - Resolve truncating stores
23888 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23889                                     const X86Subtarget *Subtarget) {
23890   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23891   if (!Mst->isTruncatingStore())
23892     return SDValue();
23893
23894   EVT VT = Mst->getValue().getValueType();
23895   unsigned NumElems = VT.getVectorNumElements();
23896   EVT StVT = Mst->getMemoryVT();
23897   SDLoc dl(Mst);
23898
23899   assert(StVT != VT && "Cannot truncate to the same type");
23900   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23901   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23902
23903   // From, To sizes and ElemCount must be pow of two
23904   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23905     "Unexpected size for truncating masked store");
23906   // We are going to use the original vector elt for storing.
23907   // Accumulated smaller vector elements must be a multiple of the store size.
23908   assert (((NumElems * FromSz) % ToSz) == 0 &&
23909           "Unexpected ratio for truncating masked store");
23910
23911   unsigned SizeRatio  = FromSz / ToSz;
23912   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23913
23914   // Create a type on which we perform the shuffle
23915   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23916           StVT.getScalarType(), NumElems*SizeRatio);
23917
23918   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23919
23920   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
23921   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23922   for (unsigned i = 0; i != NumElems; ++i)
23923     ShuffleVec[i] = i * SizeRatio;
23924
23925   // Can't shuffle using an illegal type.
23926   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23927           && "WideVecVT should be legal");
23928
23929   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23930                                         DAG.getUNDEF(WideVecVT),
23931                                         &ShuffleVec[0]);
23932
23933   SDValue NewMask;
23934   SDValue Mask = Mst->getMask();
23935   if (Mask.getValueType() == VT) {
23936     // Mask and original value have the same type
23937     NewMask = DAG.getBitcast(WideVecVT, Mask);
23938     for (unsigned i = 0; i != NumElems; ++i)
23939       ShuffleVec[i] = i * SizeRatio;
23940     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23941       ShuffleVec[i] = NumElems*SizeRatio;
23942     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23943                                    DAG.getConstant(0, dl, WideVecVT),
23944                                    &ShuffleVec[0]);
23945   }
23946   else {
23947     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23948     unsigned WidenNumElts = NumElems*SizeRatio;
23949     unsigned MaskNumElts = VT.getVectorNumElements();
23950     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23951                                      WidenNumElts);
23952
23953     unsigned NumConcat = WidenNumElts / MaskNumElts;
23954     SmallVector<SDValue, 16> Ops(NumConcat);
23955     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23956     Ops[0] = Mask;
23957     for (unsigned i = 1; i != NumConcat; ++i)
23958       Ops[i] = ZeroVal;
23959
23960     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23961   }
23962
23963   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23964                             NewMask, StVT, Mst->getMemOperand(), false);
23965 }
23966 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23967 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23968                                    const X86Subtarget *Subtarget) {
23969   StoreSDNode *St = cast<StoreSDNode>(N);
23970   EVT VT = St->getValue().getValueType();
23971   EVT StVT = St->getMemoryVT();
23972   SDLoc dl(St);
23973   SDValue StoredVal = St->getOperand(1);
23974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23975
23976   // If we are saving a concatenation of two XMM registers and 32-byte stores
23977   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23978   unsigned Alignment = St->getAlignment();
23979   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23980   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23981       StVT == VT && !IsAligned) {
23982     unsigned NumElems = VT.getVectorNumElements();
23983     if (NumElems < 2)
23984       return SDValue();
23985
23986     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23987     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23988
23989     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23990     SDValue Ptr0 = St->getBasePtr();
23991     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23992
23993     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23994                                 St->getPointerInfo(), St->isVolatile(),
23995                                 St->isNonTemporal(), Alignment);
23996     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23997                                 St->getPointerInfo(), St->isVolatile(),
23998                                 St->isNonTemporal(),
23999                                 std::min(16U, Alignment));
24000     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24001   }
24002
24003   // Optimize trunc store (of multiple scalars) to shuffle and store.
24004   // First, pack all of the elements in one place. Next, store to memory
24005   // in fewer chunks.
24006   if (St->isTruncatingStore() && VT.isVector()) {
24007     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24008     unsigned NumElems = VT.getVectorNumElements();
24009     assert(StVT != VT && "Cannot truncate to the same type");
24010     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24011     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24012
24013     // From, To sizes and ElemCount must be pow of two
24014     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24015     // We are going to use the original vector elt for storing.
24016     // Accumulated smaller vector elements must be a multiple of the store size.
24017     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24018
24019     unsigned SizeRatio  = FromSz / ToSz;
24020
24021     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24022
24023     // Create a type on which we perform the shuffle
24024     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24025             StVT.getScalarType(), NumElems*SizeRatio);
24026
24027     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24028
24029     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24030     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24031     for (unsigned i = 0; i != NumElems; ++i)
24032       ShuffleVec[i] = i * SizeRatio;
24033
24034     // Can't shuffle using an illegal type.
24035     if (!TLI.isTypeLegal(WideVecVT))
24036       return SDValue();
24037
24038     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24039                                          DAG.getUNDEF(WideVecVT),
24040                                          &ShuffleVec[0]);
24041     // At this point all of the data is stored at the bottom of the
24042     // register. We now need to save it to mem.
24043
24044     // Find the largest store unit
24045     MVT StoreType = MVT::i8;
24046     for (MVT Tp : MVT::integer_valuetypes()) {
24047       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24048         StoreType = Tp;
24049     }
24050
24051     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24052     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24053         (64 <= NumElems * ToSz))
24054       StoreType = MVT::f64;
24055
24056     // Bitcast the original vector into a vector of store-size units
24057     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24058             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24059     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24060     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24061     SmallVector<SDValue, 8> Chains;
24062     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
24063                                         TLI.getPointerTy());
24064     SDValue Ptr = St->getBasePtr();
24065
24066     // Perform one or more big stores into memory.
24067     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24068       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24069                                    StoreType, ShuffWide,
24070                                    DAG.getIntPtrConstant(i, dl));
24071       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24072                                 St->getPointerInfo(), St->isVolatile(),
24073                                 St->isNonTemporal(), St->getAlignment());
24074       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24075       Chains.push_back(Ch);
24076     }
24077
24078     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24079   }
24080
24081   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24082   // the FP state in cases where an emms may be missing.
24083   // A preferable solution to the general problem is to figure out the right
24084   // places to insert EMMS.  This qualifies as a quick hack.
24085
24086   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24087   if (VT.getSizeInBits() != 64)
24088     return SDValue();
24089
24090   const Function *F = DAG.getMachineFunction().getFunction();
24091   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24092   bool F64IsLegal =
24093       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24094   if ((VT.isVector() ||
24095        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24096       isa<LoadSDNode>(St->getValue()) &&
24097       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24098       St->getChain().hasOneUse() && !St->isVolatile()) {
24099     SDNode* LdVal = St->getValue().getNode();
24100     LoadSDNode *Ld = nullptr;
24101     int TokenFactorIndex = -1;
24102     SmallVector<SDValue, 8> Ops;
24103     SDNode* ChainVal = St->getChain().getNode();
24104     // Must be a store of a load.  We currently handle two cases:  the load
24105     // is a direct child, and it's under an intervening TokenFactor.  It is
24106     // possible to dig deeper under nested TokenFactors.
24107     if (ChainVal == LdVal)
24108       Ld = cast<LoadSDNode>(St->getChain());
24109     else if (St->getValue().hasOneUse() &&
24110              ChainVal->getOpcode() == ISD::TokenFactor) {
24111       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24112         if (ChainVal->getOperand(i).getNode() == LdVal) {
24113           TokenFactorIndex = i;
24114           Ld = cast<LoadSDNode>(St->getValue());
24115         } else
24116           Ops.push_back(ChainVal->getOperand(i));
24117       }
24118     }
24119
24120     if (!Ld || !ISD::isNormalLoad(Ld))
24121       return SDValue();
24122
24123     // If this is not the MMX case, i.e. we are just turning i64 load/store
24124     // into f64 load/store, avoid the transformation if there are multiple
24125     // uses of the loaded value.
24126     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24127       return SDValue();
24128
24129     SDLoc LdDL(Ld);
24130     SDLoc StDL(N);
24131     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24132     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24133     // pair instead.
24134     if (Subtarget->is64Bit() || F64IsLegal) {
24135       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24136       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24137                                   Ld->getPointerInfo(), Ld->isVolatile(),
24138                                   Ld->isNonTemporal(), Ld->isInvariant(),
24139                                   Ld->getAlignment());
24140       SDValue NewChain = NewLd.getValue(1);
24141       if (TokenFactorIndex != -1) {
24142         Ops.push_back(NewChain);
24143         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24144       }
24145       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24146                           St->getPointerInfo(),
24147                           St->isVolatile(), St->isNonTemporal(),
24148                           St->getAlignment());
24149     }
24150
24151     // Otherwise, lower to two pairs of 32-bit loads / stores.
24152     SDValue LoAddr = Ld->getBasePtr();
24153     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24154                                  DAG.getConstant(4, LdDL, MVT::i32));
24155
24156     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24157                                Ld->getPointerInfo(),
24158                                Ld->isVolatile(), Ld->isNonTemporal(),
24159                                Ld->isInvariant(), Ld->getAlignment());
24160     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24161                                Ld->getPointerInfo().getWithOffset(4),
24162                                Ld->isVolatile(), Ld->isNonTemporal(),
24163                                Ld->isInvariant(),
24164                                MinAlign(Ld->getAlignment(), 4));
24165
24166     SDValue NewChain = LoLd.getValue(1);
24167     if (TokenFactorIndex != -1) {
24168       Ops.push_back(LoLd);
24169       Ops.push_back(HiLd);
24170       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24171     }
24172
24173     LoAddr = St->getBasePtr();
24174     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24175                          DAG.getConstant(4, StDL, MVT::i32));
24176
24177     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24178                                 St->getPointerInfo(),
24179                                 St->isVolatile(), St->isNonTemporal(),
24180                                 St->getAlignment());
24181     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24182                                 St->getPointerInfo().getWithOffset(4),
24183                                 St->isVolatile(),
24184                                 St->isNonTemporal(),
24185                                 MinAlign(St->getAlignment(), 4));
24186     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24187   }
24188
24189   // This is similar to the above case, but here we handle a scalar 64-bit
24190   // integer store that is extracted from a vector on a 32-bit target.
24191   // If we have SSE2, then we can treat it like a floating-point double
24192   // to get past legalization. The execution dependencies fixup pass will
24193   // choose the optimal machine instruction for the store if this really is
24194   // an integer or v2f32 rather than an f64.
24195   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24196       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24197     SDValue OldExtract = St->getOperand(1);
24198     SDValue ExtOp0 = OldExtract.getOperand(0);
24199     unsigned VecSize = ExtOp0.getValueSizeInBits();
24200     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24201     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24202     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24203                                      BitCast, OldExtract.getOperand(1));
24204     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24205                         St->getPointerInfo(), St->isVolatile(),
24206                         St->isNonTemporal(), St->getAlignment());
24207   }
24208
24209   return SDValue();
24210 }
24211
24212 /// Return 'true' if this vector operation is "horizontal"
24213 /// and return the operands for the horizontal operation in LHS and RHS.  A
24214 /// horizontal operation performs the binary operation on successive elements
24215 /// of its first operand, then on successive elements of its second operand,
24216 /// returning the resulting values in a vector.  For example, if
24217 ///   A = < float a0, float a1, float a2, float a3 >
24218 /// and
24219 ///   B = < float b0, float b1, float b2, float b3 >
24220 /// then the result of doing a horizontal operation on A and B is
24221 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24222 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24223 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24224 /// set to A, RHS to B, and the routine returns 'true'.
24225 /// Note that the binary operation should have the property that if one of the
24226 /// operands is UNDEF then the result is UNDEF.
24227 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24228   // Look for the following pattern: if
24229   //   A = < float a0, float a1, float a2, float a3 >
24230   //   B = < float b0, float b1, float b2, float b3 >
24231   // and
24232   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24233   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24234   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24235   // which is A horizontal-op B.
24236
24237   // At least one of the operands should be a vector shuffle.
24238   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24239       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24240     return false;
24241
24242   MVT VT = LHS.getSimpleValueType();
24243
24244   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24245          "Unsupported vector type for horizontal add/sub");
24246
24247   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24248   // operate independently on 128-bit lanes.
24249   unsigned NumElts = VT.getVectorNumElements();
24250   unsigned NumLanes = VT.getSizeInBits()/128;
24251   unsigned NumLaneElts = NumElts / NumLanes;
24252   assert((NumLaneElts % 2 == 0) &&
24253          "Vector type should have an even number of elements in each lane");
24254   unsigned HalfLaneElts = NumLaneElts/2;
24255
24256   // View LHS in the form
24257   //   LHS = VECTOR_SHUFFLE A, B, LMask
24258   // If LHS is not a shuffle then pretend it is the shuffle
24259   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24260   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24261   // type VT.
24262   SDValue A, B;
24263   SmallVector<int, 16> LMask(NumElts);
24264   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24265     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24266       A = LHS.getOperand(0);
24267     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24268       B = LHS.getOperand(1);
24269     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24270     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24271   } else {
24272     if (LHS.getOpcode() != ISD::UNDEF)
24273       A = LHS;
24274     for (unsigned i = 0; i != NumElts; ++i)
24275       LMask[i] = i;
24276   }
24277
24278   // Likewise, view RHS in the form
24279   //   RHS = VECTOR_SHUFFLE C, D, RMask
24280   SDValue C, D;
24281   SmallVector<int, 16> RMask(NumElts);
24282   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24283     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24284       C = RHS.getOperand(0);
24285     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24286       D = RHS.getOperand(1);
24287     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24288     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24289   } else {
24290     if (RHS.getOpcode() != ISD::UNDEF)
24291       C = RHS;
24292     for (unsigned i = 0; i != NumElts; ++i)
24293       RMask[i] = i;
24294   }
24295
24296   // Check that the shuffles are both shuffling the same vectors.
24297   if (!(A == C && B == D) && !(A == D && B == C))
24298     return false;
24299
24300   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24301   if (!A.getNode() && !B.getNode())
24302     return false;
24303
24304   // If A and B occur in reverse order in RHS, then "swap" them (which means
24305   // rewriting the mask).
24306   if (A != C)
24307     ShuffleVectorSDNode::commuteMask(RMask);
24308
24309   // At this point LHS and RHS are equivalent to
24310   //   LHS = VECTOR_SHUFFLE A, B, LMask
24311   //   RHS = VECTOR_SHUFFLE A, B, RMask
24312   // Check that the masks correspond to performing a horizontal operation.
24313   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24314     for (unsigned i = 0; i != NumLaneElts; ++i) {
24315       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24316
24317       // Ignore any UNDEF components.
24318       if (LIdx < 0 || RIdx < 0 ||
24319           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24320           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24321         continue;
24322
24323       // Check that successive elements are being operated on.  If not, this is
24324       // not a horizontal operation.
24325       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24326       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24327       if (!(LIdx == Index && RIdx == Index + 1) &&
24328           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24329         return false;
24330     }
24331   }
24332
24333   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24334   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24335   return true;
24336 }
24337
24338 /// Do target-specific dag combines on floating point adds.
24339 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24340                                   const X86Subtarget *Subtarget) {
24341   EVT VT = N->getValueType(0);
24342   SDValue LHS = N->getOperand(0);
24343   SDValue RHS = N->getOperand(1);
24344
24345   // Try to synthesize horizontal adds from adds of shuffles.
24346   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24347        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24348       isHorizontalBinOp(LHS, RHS, true))
24349     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24350   return SDValue();
24351 }
24352
24353 /// Do target-specific dag combines on floating point subs.
24354 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24355                                   const X86Subtarget *Subtarget) {
24356   EVT VT = N->getValueType(0);
24357   SDValue LHS = N->getOperand(0);
24358   SDValue RHS = N->getOperand(1);
24359
24360   // Try to synthesize horizontal subs from subs of shuffles.
24361   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24362        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24363       isHorizontalBinOp(LHS, RHS, false))
24364     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24365   return SDValue();
24366 }
24367
24368 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24369 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24370   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24371
24372   // F[X]OR(0.0, x) -> x
24373   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24374     if (C->getValueAPF().isPosZero())
24375       return N->getOperand(1);
24376
24377   // F[X]OR(x, 0.0) -> x
24378   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24379     if (C->getValueAPF().isPosZero())
24380       return N->getOperand(0);
24381   return SDValue();
24382 }
24383
24384 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24385 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24386   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24387
24388   // Only perform optimizations if UnsafeMath is used.
24389   if (!DAG.getTarget().Options.UnsafeFPMath)
24390     return SDValue();
24391
24392   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24393   // into FMINC and FMAXC, which are Commutative operations.
24394   unsigned NewOp = 0;
24395   switch (N->getOpcode()) {
24396     default: llvm_unreachable("unknown opcode");
24397     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24398     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24399   }
24400
24401   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24402                      N->getOperand(0), N->getOperand(1));
24403 }
24404
24405 /// Do target-specific dag combines on X86ISD::FAND nodes.
24406 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24407   // FAND(0.0, x) -> 0.0
24408   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24409     if (C->getValueAPF().isPosZero())
24410       return N->getOperand(0);
24411
24412   // FAND(x, 0.0) -> 0.0
24413   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24414     if (C->getValueAPF().isPosZero())
24415       return N->getOperand(1);
24416
24417   return SDValue();
24418 }
24419
24420 /// Do target-specific dag combines on X86ISD::FANDN nodes
24421 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24422   // FANDN(0.0, x) -> x
24423   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24424     if (C->getValueAPF().isPosZero())
24425       return N->getOperand(1);
24426
24427   // FANDN(x, 0.0) -> 0.0
24428   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24429     if (C->getValueAPF().isPosZero())
24430       return N->getOperand(1);
24431
24432   return SDValue();
24433 }
24434
24435 static SDValue PerformBTCombine(SDNode *N,
24436                                 SelectionDAG &DAG,
24437                                 TargetLowering::DAGCombinerInfo &DCI) {
24438   // BT ignores high bits in the bit index operand.
24439   SDValue Op1 = N->getOperand(1);
24440   if (Op1.hasOneUse()) {
24441     unsigned BitWidth = Op1.getValueSizeInBits();
24442     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24443     APInt KnownZero, KnownOne;
24444     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24445                                           !DCI.isBeforeLegalizeOps());
24446     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24447     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24448         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24449       DCI.CommitTargetLoweringOpt(TLO);
24450   }
24451   return SDValue();
24452 }
24453
24454 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24455   SDValue Op = N->getOperand(0);
24456   if (Op.getOpcode() == ISD::BITCAST)
24457     Op = Op.getOperand(0);
24458   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24459   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24460       VT.getVectorElementType().getSizeInBits() ==
24461       OpVT.getVectorElementType().getSizeInBits()) {
24462     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24463   }
24464   return SDValue();
24465 }
24466
24467 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24468                                                const X86Subtarget *Subtarget) {
24469   EVT VT = N->getValueType(0);
24470   if (!VT.isVector())
24471     return SDValue();
24472
24473   SDValue N0 = N->getOperand(0);
24474   SDValue N1 = N->getOperand(1);
24475   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24476   SDLoc dl(N);
24477
24478   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24479   // both SSE and AVX2 since there is no sign-extended shift right
24480   // operation on a vector with 64-bit elements.
24481   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24482   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24483   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24484       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24485     SDValue N00 = N0.getOperand(0);
24486
24487     // EXTLOAD has a better solution on AVX2,
24488     // it may be replaced with X86ISD::VSEXT node.
24489     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24490       if (!ISD::isNormalLoad(N00.getNode()))
24491         return SDValue();
24492
24493     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24494         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24495                                   N00, N1);
24496       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24497     }
24498   }
24499   return SDValue();
24500 }
24501
24502 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24503                                   TargetLowering::DAGCombinerInfo &DCI,
24504                                   const X86Subtarget *Subtarget) {
24505   SDValue N0 = N->getOperand(0);
24506   EVT VT = N->getValueType(0);
24507   EVT SVT = VT.getScalarType();
24508   EVT InVT = N0.getValueType();
24509   EVT InSVT = InVT.getScalarType();
24510   SDLoc DL(N);
24511
24512   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24513   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24514   // This exposes the sext to the sdivrem lowering, so that it directly extends
24515   // from AH (which we otherwise need to do contortions to access).
24516   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24517       InVT == MVT::i8 && VT == MVT::i32) {
24518     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24519     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24520                             N0.getOperand(0), N0.getOperand(1));
24521     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24522     return R.getValue(1);
24523   }
24524
24525   if (!DCI.isBeforeLegalizeOps()) {
24526     if (InVT == MVT::i1) {
24527       SDValue Zero = DAG.getConstant(0, DL, VT);
24528       SDValue AllOnes =
24529         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24530       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24531     }
24532     return SDValue();
24533   }
24534
24535   if (VT.isVector() && Subtarget->hasSSE2()) {
24536     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24537       EVT InVT = N.getValueType();
24538       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24539                                    Size / InVT.getScalarSizeInBits());
24540       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24541                                     DAG.getUNDEF(InVT));
24542       Opnds[0] = N;
24543       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24544     };
24545
24546     // If target-size is less than 128-bits, extend to a type that would extend
24547     // to 128 bits, extend that and extract the original target vector.
24548     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24549         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24550         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24551       unsigned Scale = 128 / VT.getSizeInBits();
24552       EVT ExVT =
24553           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24554       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24555       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24556       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24557                          DAG.getIntPtrConstant(0, DL));
24558     }
24559
24560     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24561     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24562     if (VT.getSizeInBits() == 128 &&
24563         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24564         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24565       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24566       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24567     }
24568
24569     // On pre-AVX2 targets, split into 128-bit nodes of
24570     // ISD::SIGN_EXTEND_VECTOR_INREG.
24571     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24572         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24573         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24574       unsigned NumVecs = VT.getSizeInBits() / 128;
24575       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24576       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24577       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24578
24579       SmallVector<SDValue, 8> Opnds;
24580       for (unsigned i = 0, Offset = 0; i != NumVecs;
24581            ++i, Offset += NumSubElts) {
24582         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24583                                      DAG.getIntPtrConstant(Offset, DL));
24584         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24585         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24586         Opnds.push_back(SrcVec);
24587       }
24588       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24589     }
24590   }
24591
24592   if (!Subtarget->hasFp256())
24593     return SDValue();
24594
24595   if (VT.isVector() && VT.getSizeInBits() == 256)
24596     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24597       return R;
24598
24599   return SDValue();
24600 }
24601
24602 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24603                                  const X86Subtarget* Subtarget) {
24604   SDLoc dl(N);
24605   EVT VT = N->getValueType(0);
24606
24607   // Let legalize expand this if it isn't a legal type yet.
24608   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24609     return SDValue();
24610
24611   EVT ScalarVT = VT.getScalarType();
24612   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24613       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24614        !Subtarget->hasAVX512()))
24615     return SDValue();
24616
24617   SDValue A = N->getOperand(0);
24618   SDValue B = N->getOperand(1);
24619   SDValue C = N->getOperand(2);
24620
24621   bool NegA = (A.getOpcode() == ISD::FNEG);
24622   bool NegB = (B.getOpcode() == ISD::FNEG);
24623   bool NegC = (C.getOpcode() == ISD::FNEG);
24624
24625   // Negative multiplication when NegA xor NegB
24626   bool NegMul = (NegA != NegB);
24627   if (NegA)
24628     A = A.getOperand(0);
24629   if (NegB)
24630     B = B.getOperand(0);
24631   if (NegC)
24632     C = C.getOperand(0);
24633
24634   unsigned Opcode;
24635   if (!NegMul)
24636     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24637   else
24638     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24639
24640   return DAG.getNode(Opcode, dl, VT, A, B, C);
24641 }
24642
24643 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24644                                   TargetLowering::DAGCombinerInfo &DCI,
24645                                   const X86Subtarget *Subtarget) {
24646   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24647   //           (and (i32 x86isd::setcc_carry), 1)
24648   // This eliminates the zext. This transformation is necessary because
24649   // ISD::SETCC is always legalized to i8.
24650   SDLoc dl(N);
24651   SDValue N0 = N->getOperand(0);
24652   EVT VT = N->getValueType(0);
24653
24654   if (N0.getOpcode() == ISD::AND &&
24655       N0.hasOneUse() &&
24656       N0.getOperand(0).hasOneUse()) {
24657     SDValue N00 = N0.getOperand(0);
24658     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24659       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24660       if (!C || C->getZExtValue() != 1)
24661         return SDValue();
24662       return DAG.getNode(ISD::AND, dl, VT,
24663                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24664                                      N00.getOperand(0), N00.getOperand(1)),
24665                          DAG.getConstant(1, dl, VT));
24666     }
24667   }
24668
24669   if (N0.getOpcode() == ISD::TRUNCATE &&
24670       N0.hasOneUse() &&
24671       N0.getOperand(0).hasOneUse()) {
24672     SDValue N00 = N0.getOperand(0);
24673     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24674       return DAG.getNode(ISD::AND, dl, VT,
24675                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24676                                      N00.getOperand(0), N00.getOperand(1)),
24677                          DAG.getConstant(1, dl, VT));
24678     }
24679   }
24680
24681   if (VT.is256BitVector())
24682     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24683       return R;
24684
24685   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24686   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24687   // This exposes the zext to the udivrem lowering, so that it directly extends
24688   // from AH (which we otherwise need to do contortions to access).
24689   if (N0.getOpcode() == ISD::UDIVREM &&
24690       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24691       (VT == MVT::i32 || VT == MVT::i64)) {
24692     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24693     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24694                             N0.getOperand(0), N0.getOperand(1));
24695     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24696     return R.getValue(1);
24697   }
24698
24699   return SDValue();
24700 }
24701
24702 // Optimize x == -y --> x+y == 0
24703 //          x != -y --> x+y != 0
24704 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24705                                       const X86Subtarget* Subtarget) {
24706   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24707   SDValue LHS = N->getOperand(0);
24708   SDValue RHS = N->getOperand(1);
24709   EVT VT = N->getValueType(0);
24710   SDLoc DL(N);
24711
24712   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24713     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24714       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24715         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24716                                    LHS.getOperand(1));
24717         return DAG.getSetCC(DL, N->getValueType(0), addV,
24718                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24719       }
24720   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24721     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24722       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24723         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24724                                    RHS.getOperand(1));
24725         return DAG.getSetCC(DL, N->getValueType(0), addV,
24726                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24727       }
24728
24729   if (VT.getScalarType() == MVT::i1 &&
24730       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24731     bool IsSEXT0 =
24732         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24733         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24734     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24735
24736     if (!IsSEXT0 || !IsVZero1) {
24737       // Swap the operands and update the condition code.
24738       std::swap(LHS, RHS);
24739       CC = ISD::getSetCCSwappedOperands(CC);
24740
24741       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24742                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24743       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24744     }
24745
24746     if (IsSEXT0 && IsVZero1) {
24747       assert(VT == LHS.getOperand(0).getValueType() &&
24748              "Uexpected operand type");
24749       if (CC == ISD::SETGT)
24750         return DAG.getConstant(0, DL, VT);
24751       if (CC == ISD::SETLE)
24752         return DAG.getConstant(1, DL, VT);
24753       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24754         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24755
24756       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24757              "Unexpected condition code!");
24758       return LHS.getOperand(0);
24759     }
24760   }
24761
24762   return SDValue();
24763 }
24764
24765 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24766                                          SelectionDAG &DAG) {
24767   SDLoc dl(Load);
24768   MVT VT = Load->getSimpleValueType(0);
24769   MVT EVT = VT.getVectorElementType();
24770   SDValue Addr = Load->getOperand(1);
24771   SDValue NewAddr = DAG.getNode(
24772       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24773       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24774                       Addr.getSimpleValueType()));
24775
24776   SDValue NewLoad =
24777       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24778                   DAG.getMachineFunction().getMachineMemOperand(
24779                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24780   return NewLoad;
24781 }
24782
24783 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24784                                       const X86Subtarget *Subtarget) {
24785   SDLoc dl(N);
24786   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24787   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24788          "X86insertps is only defined for v4x32");
24789
24790   SDValue Ld = N->getOperand(1);
24791   if (MayFoldLoad(Ld)) {
24792     // Extract the countS bits from the immediate so we can get the proper
24793     // address when narrowing the vector load to a specific element.
24794     // When the second source op is a memory address, insertps doesn't use
24795     // countS and just gets an f32 from that address.
24796     unsigned DestIndex =
24797         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24798
24799     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24800
24801     // Create this as a scalar to vector to match the instruction pattern.
24802     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24803     // countS bits are ignored when loading from memory on insertps, which
24804     // means we don't need to explicitly set them to 0.
24805     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24806                        LoadScalarToVector, N->getOperand(2));
24807   }
24808   return SDValue();
24809 }
24810
24811 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24812   SDValue V0 = N->getOperand(0);
24813   SDValue V1 = N->getOperand(1);
24814   SDLoc DL(N);
24815   EVT VT = N->getValueType(0);
24816
24817   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24818   // operands and changing the mask to 1. This saves us a bunch of
24819   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24820   // x86InstrInfo knows how to commute this back after instruction selection
24821   // if it would help register allocation.
24822
24823   // TODO: If optimizing for size or a processor that doesn't suffer from
24824   // partial register update stalls, this should be transformed into a MOVSD
24825   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24826
24827   if (VT == MVT::v2f64)
24828     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24829       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24830         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24831         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24832       }
24833
24834   return SDValue();
24835 }
24836
24837 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24838 // as "sbb reg,reg", since it can be extended without zext and produces
24839 // an all-ones bit which is more useful than 0/1 in some cases.
24840 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24841                                MVT VT) {
24842   if (VT == MVT::i8)
24843     return DAG.getNode(ISD::AND, DL, VT,
24844                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24845                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24846                                    EFLAGS),
24847                        DAG.getConstant(1, DL, VT));
24848   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24849   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24850                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24851                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24852                                  EFLAGS));
24853 }
24854
24855 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24856 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24857                                    TargetLowering::DAGCombinerInfo &DCI,
24858                                    const X86Subtarget *Subtarget) {
24859   SDLoc DL(N);
24860   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24861   SDValue EFLAGS = N->getOperand(1);
24862
24863   if (CC == X86::COND_A) {
24864     // Try to convert COND_A into COND_B in an attempt to facilitate
24865     // materializing "setb reg".
24866     //
24867     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24868     // cannot take an immediate as its first operand.
24869     //
24870     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24871         EFLAGS.getValueType().isInteger() &&
24872         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24873       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24874                                    EFLAGS.getNode()->getVTList(),
24875                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24876       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24877       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24878     }
24879   }
24880
24881   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24882   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24883   // cases.
24884   if (CC == X86::COND_B)
24885     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24886
24887   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24888     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24889     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24890   }
24891
24892   return SDValue();
24893 }
24894
24895 // Optimize branch condition evaluation.
24896 //
24897 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24898                                     TargetLowering::DAGCombinerInfo &DCI,
24899                                     const X86Subtarget *Subtarget) {
24900   SDLoc DL(N);
24901   SDValue Chain = N->getOperand(0);
24902   SDValue Dest = N->getOperand(1);
24903   SDValue EFLAGS = N->getOperand(3);
24904   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24905
24906   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24907     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24908     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24909                        Flags);
24910   }
24911
24912   return SDValue();
24913 }
24914
24915 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24916                                                          SelectionDAG &DAG) {
24917   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24918   // optimize away operation when it's from a constant.
24919   //
24920   // The general transformation is:
24921   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24922   //       AND(VECTOR_CMP(x,y), constant2)
24923   //    constant2 = UNARYOP(constant)
24924
24925   // Early exit if this isn't a vector operation, the operand of the
24926   // unary operation isn't a bitwise AND, or if the sizes of the operations
24927   // aren't the same.
24928   EVT VT = N->getValueType(0);
24929   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24930       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24931       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24932     return SDValue();
24933
24934   // Now check that the other operand of the AND is a constant. We could
24935   // make the transformation for non-constant splats as well, but it's unclear
24936   // that would be a benefit as it would not eliminate any operations, just
24937   // perform one more step in scalar code before moving to the vector unit.
24938   if (BuildVectorSDNode *BV =
24939           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24940     // Bail out if the vector isn't a constant.
24941     if (!BV->isConstant())
24942       return SDValue();
24943
24944     // Everything checks out. Build up the new and improved node.
24945     SDLoc DL(N);
24946     EVT IntVT = BV->getValueType(0);
24947     // Create a new constant of the appropriate type for the transformed
24948     // DAG.
24949     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24950     // The AND node needs bitcasts to/from an integer vector type around it.
24951     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
24952     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24953                                  N->getOperand(0)->getOperand(0), MaskConst);
24954     SDValue Res = DAG.getBitcast(VT, NewAnd);
24955     return Res;
24956   }
24957
24958   return SDValue();
24959 }
24960
24961 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24962                                         const X86Subtarget *Subtarget) {
24963   SDValue Op0 = N->getOperand(0);
24964   EVT VT = N->getValueType(0);
24965   EVT InVT = Op0.getValueType();
24966   EVT InSVT = InVT.getScalarType();
24967   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24968
24969   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
24970   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
24971   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
24972     SDLoc dl(N);
24973     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
24974                                  InVT.getVectorNumElements());
24975     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
24976
24977     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
24978       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
24979
24980     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
24981   }
24982
24983   return SDValue();
24984 }
24985
24986 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24987                                         const X86Subtarget *Subtarget) {
24988   // First try to optimize away the conversion entirely when it's
24989   // conditionally from a constant. Vectors only.
24990   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
24991     return Res;
24992
24993   // Now move on to more general possibilities.
24994   SDValue Op0 = N->getOperand(0);
24995   EVT VT = N->getValueType(0);
24996   EVT InVT = Op0.getValueType();
24997   EVT InSVT = InVT.getScalarType();
24998
24999   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25000   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25001   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25002     SDLoc dl(N);
25003     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25004                                  InVT.getVectorNumElements());
25005     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25006     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25007   }
25008
25009   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25010   // a 32-bit target where SSE doesn't support i64->FP operations.
25011   if (Op0.getOpcode() == ISD::LOAD) {
25012     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25013     EVT LdVT = Ld->getValueType(0);
25014
25015     // This transformation is not supported if the result type is f16
25016     if (VT == MVT::f16)
25017       return SDValue();
25018
25019     if (!Ld->isVolatile() && !VT.isVector() &&
25020         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25021         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25022       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25023           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25024       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25025       return FILDChain;
25026     }
25027   }
25028   return SDValue();
25029 }
25030
25031 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25032 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25033                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25034   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25035   // the result is either zero or one (depending on the input carry bit).
25036   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25037   if (X86::isZeroNode(N->getOperand(0)) &&
25038       X86::isZeroNode(N->getOperand(1)) &&
25039       // We don't have a good way to replace an EFLAGS use, so only do this when
25040       // dead right now.
25041       SDValue(N, 1).use_empty()) {
25042     SDLoc DL(N);
25043     EVT VT = N->getValueType(0);
25044     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25045     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25046                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25047                                            DAG.getConstant(X86::COND_B, DL,
25048                                                            MVT::i8),
25049                                            N->getOperand(2)),
25050                                DAG.getConstant(1, DL, VT));
25051     return DCI.CombineTo(N, Res1, CarryOut);
25052   }
25053
25054   return SDValue();
25055 }
25056
25057 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25058 //      (add Y, (setne X, 0)) -> sbb -1, Y
25059 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25060 //      (sub (setne X, 0), Y) -> adc -1, Y
25061 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25062   SDLoc DL(N);
25063
25064   // Look through ZExts.
25065   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25066   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25067     return SDValue();
25068
25069   SDValue SetCC = Ext.getOperand(0);
25070   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25071     return SDValue();
25072
25073   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25074   if (CC != X86::COND_E && CC != X86::COND_NE)
25075     return SDValue();
25076
25077   SDValue Cmp = SetCC.getOperand(1);
25078   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25079       !X86::isZeroNode(Cmp.getOperand(1)) ||
25080       !Cmp.getOperand(0).getValueType().isInteger())
25081     return SDValue();
25082
25083   SDValue CmpOp0 = Cmp.getOperand(0);
25084   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25085                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25086
25087   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25088   if (CC == X86::COND_NE)
25089     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25090                        DL, OtherVal.getValueType(), OtherVal,
25091                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25092                        NewCmp);
25093   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25094                      DL, OtherVal.getValueType(), OtherVal,
25095                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25096 }
25097
25098 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25099 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25100                                  const X86Subtarget *Subtarget) {
25101   EVT VT = N->getValueType(0);
25102   SDValue Op0 = N->getOperand(0);
25103   SDValue Op1 = N->getOperand(1);
25104
25105   // Try to synthesize horizontal adds from adds of shuffles.
25106   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25107        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25108       isHorizontalBinOp(Op0, Op1, true))
25109     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25110
25111   return OptimizeConditionalInDecrement(N, DAG);
25112 }
25113
25114 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25115                                  const X86Subtarget *Subtarget) {
25116   SDValue Op0 = N->getOperand(0);
25117   SDValue Op1 = N->getOperand(1);
25118
25119   // X86 can't encode an immediate LHS of a sub. See if we can push the
25120   // negation into a preceding instruction.
25121   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25122     // If the RHS of the sub is a XOR with one use and a constant, invert the
25123     // immediate. Then add one to the LHS of the sub so we can turn
25124     // X-Y -> X+~Y+1, saving one register.
25125     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25126         isa<ConstantSDNode>(Op1.getOperand(1))) {
25127       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25128       EVT VT = Op0.getValueType();
25129       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25130                                    Op1.getOperand(0),
25131                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25132       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25133                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25134     }
25135   }
25136
25137   // Try to synthesize horizontal adds from adds of shuffles.
25138   EVT VT = N->getValueType(0);
25139   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25140        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25141       isHorizontalBinOp(Op0, Op1, true))
25142     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25143
25144   return OptimizeConditionalInDecrement(N, DAG);
25145 }
25146
25147 /// performVZEXTCombine - Performs build vector combines
25148 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25149                                    TargetLowering::DAGCombinerInfo &DCI,
25150                                    const X86Subtarget *Subtarget) {
25151   SDLoc DL(N);
25152   MVT VT = N->getSimpleValueType(0);
25153   SDValue Op = N->getOperand(0);
25154   MVT OpVT = Op.getSimpleValueType();
25155   MVT OpEltVT = OpVT.getVectorElementType();
25156   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25157
25158   // (vzext (bitcast (vzext (x)) -> (vzext x)
25159   SDValue V = Op;
25160   while (V.getOpcode() == ISD::BITCAST)
25161     V = V.getOperand(0);
25162
25163   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25164     MVT InnerVT = V.getSimpleValueType();
25165     MVT InnerEltVT = InnerVT.getVectorElementType();
25166
25167     // If the element sizes match exactly, we can just do one larger vzext. This
25168     // is always an exact type match as vzext operates on integer types.
25169     if (OpEltVT == InnerEltVT) {
25170       assert(OpVT == InnerVT && "Types must match for vzext!");
25171       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25172     }
25173
25174     // The only other way we can combine them is if only a single element of the
25175     // inner vzext is used in the input to the outer vzext.
25176     if (InnerEltVT.getSizeInBits() < InputBits)
25177       return SDValue();
25178
25179     // In this case, the inner vzext is completely dead because we're going to
25180     // only look at bits inside of the low element. Just do the outer vzext on
25181     // a bitcast of the input to the inner.
25182     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25183   }
25184
25185   // Check if we can bypass extracting and re-inserting an element of an input
25186   // vector. Essentialy:
25187   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25188   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25189       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25190       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25191     SDValue ExtractedV = V.getOperand(0);
25192     SDValue OrigV = ExtractedV.getOperand(0);
25193     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25194       if (ExtractIdx->getZExtValue() == 0) {
25195         MVT OrigVT = OrigV.getSimpleValueType();
25196         // Extract a subvector if necessary...
25197         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25198           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25199           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25200                                     OrigVT.getVectorNumElements() / Ratio);
25201           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25202                               DAG.getIntPtrConstant(0, DL));
25203         }
25204         Op = DAG.getBitcast(OpVT, OrigV);
25205         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25206       }
25207   }
25208
25209   return SDValue();
25210 }
25211
25212 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25213                                              DAGCombinerInfo &DCI) const {
25214   SelectionDAG &DAG = DCI.DAG;
25215   switch (N->getOpcode()) {
25216   default: break;
25217   case ISD::EXTRACT_VECTOR_ELT:
25218     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25219   case ISD::VSELECT:
25220   case ISD::SELECT:
25221   case X86ISD::SHRUNKBLEND:
25222     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25223   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25224   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25225   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25226   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25227   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25228   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25229   case ISD::SHL:
25230   case ISD::SRA:
25231   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25232   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25233   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25234   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25235   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25236   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25237   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25238   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25239   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25240   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25241   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25242   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25243   case X86ISD::FXOR:
25244   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25245   case X86ISD::FMIN:
25246   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25247   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25248   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25249   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25250   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25251   case ISD::ANY_EXTEND:
25252   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25253   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25254   case ISD::SIGN_EXTEND_INREG:
25255     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25256   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25257   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25258   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25259   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25260   case X86ISD::SHUFP:       // Handle all target specific shuffles
25261   case X86ISD::PALIGNR:
25262   case X86ISD::UNPCKH:
25263   case X86ISD::UNPCKL:
25264   case X86ISD::MOVHLPS:
25265   case X86ISD::MOVLHPS:
25266   case X86ISD::PSHUFB:
25267   case X86ISD::PSHUFD:
25268   case X86ISD::PSHUFHW:
25269   case X86ISD::PSHUFLW:
25270   case X86ISD::MOVSS:
25271   case X86ISD::MOVSD:
25272   case X86ISD::VPERMILPI:
25273   case X86ISD::VPERM2X128:
25274   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25275   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25276   case ISD::INTRINSIC_WO_CHAIN:
25277     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25278   case X86ISD::INSERTPS: {
25279     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25280       return PerformINSERTPSCombine(N, DAG, Subtarget);
25281     break;
25282   }
25283   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25284   }
25285
25286   return SDValue();
25287 }
25288
25289 /// isTypeDesirableForOp - Return true if the target has native support for
25290 /// the specified value type and it is 'desirable' to use the type for the
25291 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25292 /// instruction encodings are longer and some i16 instructions are slow.
25293 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25294   if (!isTypeLegal(VT))
25295     return false;
25296   if (VT != MVT::i16)
25297     return true;
25298
25299   switch (Opc) {
25300   default:
25301     return true;
25302   case ISD::LOAD:
25303   case ISD::SIGN_EXTEND:
25304   case ISD::ZERO_EXTEND:
25305   case ISD::ANY_EXTEND:
25306   case ISD::SHL:
25307   case ISD::SRL:
25308   case ISD::SUB:
25309   case ISD::ADD:
25310   case ISD::MUL:
25311   case ISD::AND:
25312   case ISD::OR:
25313   case ISD::XOR:
25314     return false;
25315   }
25316 }
25317
25318 /// IsDesirableToPromoteOp - This method query the target whether it is
25319 /// beneficial for dag combiner to promote the specified node. If true, it
25320 /// should return the desired promotion type by reference.
25321 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25322   EVT VT = Op.getValueType();
25323   if (VT != MVT::i16)
25324     return false;
25325
25326   bool Promote = false;
25327   bool Commute = false;
25328   switch (Op.getOpcode()) {
25329   default: break;
25330   case ISD::LOAD: {
25331     LoadSDNode *LD = cast<LoadSDNode>(Op);
25332     // If the non-extending load has a single use and it's not live out, then it
25333     // might be folded.
25334     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25335                                                      Op.hasOneUse()*/) {
25336       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25337              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25338         // The only case where we'd want to promote LOAD (rather then it being
25339         // promoted as an operand is when it's only use is liveout.
25340         if (UI->getOpcode() != ISD::CopyToReg)
25341           return false;
25342       }
25343     }
25344     Promote = true;
25345     break;
25346   }
25347   case ISD::SIGN_EXTEND:
25348   case ISD::ZERO_EXTEND:
25349   case ISD::ANY_EXTEND:
25350     Promote = true;
25351     break;
25352   case ISD::SHL:
25353   case ISD::SRL: {
25354     SDValue N0 = Op.getOperand(0);
25355     // Look out for (store (shl (load), x)).
25356     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25357       return false;
25358     Promote = true;
25359     break;
25360   }
25361   case ISD::ADD:
25362   case ISD::MUL:
25363   case ISD::AND:
25364   case ISD::OR:
25365   case ISD::XOR:
25366     Commute = true;
25367     // fallthrough
25368   case ISD::SUB: {
25369     SDValue N0 = Op.getOperand(0);
25370     SDValue N1 = Op.getOperand(1);
25371     if (!Commute && MayFoldLoad(N1))
25372       return false;
25373     // Avoid disabling potential load folding opportunities.
25374     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25375       return false;
25376     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25377       return false;
25378     Promote = true;
25379   }
25380   }
25381
25382   PVT = MVT::i32;
25383   return Promote;
25384 }
25385
25386 //===----------------------------------------------------------------------===//
25387 //                           X86 Inline Assembly Support
25388 //===----------------------------------------------------------------------===//
25389
25390 // Helper to match a string separated by whitespace.
25391 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25392   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25393
25394   for (StringRef Piece : Pieces) {
25395     if (!S.startswith(Piece)) // Check if the piece matches.
25396       return false;
25397
25398     S = S.substr(Piece.size());
25399     StringRef::size_type Pos = S.find_first_not_of(" \t");
25400     if (Pos == 0) // We matched a prefix.
25401       return false;
25402
25403     S = S.substr(Pos);
25404   }
25405
25406   return S.empty();
25407 }
25408
25409 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25410
25411   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25412     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25413         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25414         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25415
25416       if (AsmPieces.size() == 3)
25417         return true;
25418       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25419         return true;
25420     }
25421   }
25422   return false;
25423 }
25424
25425 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25426   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25427
25428   std::string AsmStr = IA->getAsmString();
25429
25430   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25431   if (!Ty || Ty->getBitWidth() % 16 != 0)
25432     return false;
25433
25434   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25435   SmallVector<StringRef, 4> AsmPieces;
25436   SplitString(AsmStr, AsmPieces, ";\n");
25437
25438   switch (AsmPieces.size()) {
25439   default: return false;
25440   case 1:
25441     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25442     // we will turn this bswap into something that will be lowered to logical
25443     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25444     // lower so don't worry about this.
25445     // bswap $0
25446     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25447         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25448         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25449         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25450         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25451         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25452       // No need to check constraints, nothing other than the equivalent of
25453       // "=r,0" would be valid here.
25454       return IntrinsicLowering::LowerToByteSwap(CI);
25455     }
25456
25457     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25458     if (CI->getType()->isIntegerTy(16) &&
25459         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25460         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25461          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25462       AsmPieces.clear();
25463       StringRef ConstraintsStr = IA->getConstraintString();
25464       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25465       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25466       if (clobbersFlagRegisters(AsmPieces))
25467         return IntrinsicLowering::LowerToByteSwap(CI);
25468     }
25469     break;
25470   case 3:
25471     if (CI->getType()->isIntegerTy(32) &&
25472         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25473         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25474         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25475         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25476       AsmPieces.clear();
25477       StringRef ConstraintsStr = IA->getConstraintString();
25478       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25479       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25480       if (clobbersFlagRegisters(AsmPieces))
25481         return IntrinsicLowering::LowerToByteSwap(CI);
25482     }
25483
25484     if (CI->getType()->isIntegerTy(64)) {
25485       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25486       if (Constraints.size() >= 2 &&
25487           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25488           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25489         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25490         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25491             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25492             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25493           return IntrinsicLowering::LowerToByteSwap(CI);
25494       }
25495     }
25496     break;
25497   }
25498   return false;
25499 }
25500
25501 /// getConstraintType - Given a constraint letter, return the type of
25502 /// constraint it is for this target.
25503 X86TargetLowering::ConstraintType
25504 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25505   if (Constraint.size() == 1) {
25506     switch (Constraint[0]) {
25507     case 'R':
25508     case 'q':
25509     case 'Q':
25510     case 'f':
25511     case 't':
25512     case 'u':
25513     case 'y':
25514     case 'x':
25515     case 'Y':
25516     case 'l':
25517       return C_RegisterClass;
25518     case 'a':
25519     case 'b':
25520     case 'c':
25521     case 'd':
25522     case 'S':
25523     case 'D':
25524     case 'A':
25525       return C_Register;
25526     case 'I':
25527     case 'J':
25528     case 'K':
25529     case 'L':
25530     case 'M':
25531     case 'N':
25532     case 'G':
25533     case 'C':
25534     case 'e':
25535     case 'Z':
25536       return C_Other;
25537     default:
25538       break;
25539     }
25540   }
25541   return TargetLowering::getConstraintType(Constraint);
25542 }
25543
25544 /// Examine constraint type and operand type and determine a weight value.
25545 /// This object must already have been set up with the operand type
25546 /// and the current alternative constraint selected.
25547 TargetLowering::ConstraintWeight
25548   X86TargetLowering::getSingleConstraintMatchWeight(
25549     AsmOperandInfo &info, const char *constraint) const {
25550   ConstraintWeight weight = CW_Invalid;
25551   Value *CallOperandVal = info.CallOperandVal;
25552     // If we don't have a value, we can't do a match,
25553     // but allow it at the lowest weight.
25554   if (!CallOperandVal)
25555     return CW_Default;
25556   Type *type = CallOperandVal->getType();
25557   // Look at the constraint type.
25558   switch (*constraint) {
25559   default:
25560     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25561   case 'R':
25562   case 'q':
25563   case 'Q':
25564   case 'a':
25565   case 'b':
25566   case 'c':
25567   case 'd':
25568   case 'S':
25569   case 'D':
25570   case 'A':
25571     if (CallOperandVal->getType()->isIntegerTy())
25572       weight = CW_SpecificReg;
25573     break;
25574   case 'f':
25575   case 't':
25576   case 'u':
25577     if (type->isFloatingPointTy())
25578       weight = CW_SpecificReg;
25579     break;
25580   case 'y':
25581     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25582       weight = CW_SpecificReg;
25583     break;
25584   case 'x':
25585   case 'Y':
25586     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25587         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25588       weight = CW_Register;
25589     break;
25590   case 'I':
25591     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25592       if (C->getZExtValue() <= 31)
25593         weight = CW_Constant;
25594     }
25595     break;
25596   case 'J':
25597     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25598       if (C->getZExtValue() <= 63)
25599         weight = CW_Constant;
25600     }
25601     break;
25602   case 'K':
25603     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25604       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25605         weight = CW_Constant;
25606     }
25607     break;
25608   case 'L':
25609     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25610       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25611         weight = CW_Constant;
25612     }
25613     break;
25614   case 'M':
25615     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25616       if (C->getZExtValue() <= 3)
25617         weight = CW_Constant;
25618     }
25619     break;
25620   case 'N':
25621     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25622       if (C->getZExtValue() <= 0xff)
25623         weight = CW_Constant;
25624     }
25625     break;
25626   case 'G':
25627   case 'C':
25628     if (isa<ConstantFP>(CallOperandVal)) {
25629       weight = CW_Constant;
25630     }
25631     break;
25632   case 'e':
25633     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25634       if ((C->getSExtValue() >= -0x80000000LL) &&
25635           (C->getSExtValue() <= 0x7fffffffLL))
25636         weight = CW_Constant;
25637     }
25638     break;
25639   case 'Z':
25640     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25641       if (C->getZExtValue() <= 0xffffffff)
25642         weight = CW_Constant;
25643     }
25644     break;
25645   }
25646   return weight;
25647 }
25648
25649 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25650 /// with another that has more specific requirements based on the type of the
25651 /// corresponding operand.
25652 const char *X86TargetLowering::
25653 LowerXConstraint(EVT ConstraintVT) const {
25654   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25655   // 'f' like normal targets.
25656   if (ConstraintVT.isFloatingPoint()) {
25657     if (Subtarget->hasSSE2())
25658       return "Y";
25659     if (Subtarget->hasSSE1())
25660       return "x";
25661   }
25662
25663   return TargetLowering::LowerXConstraint(ConstraintVT);
25664 }
25665
25666 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25667 /// vector.  If it is invalid, don't add anything to Ops.
25668 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25669                                                      std::string &Constraint,
25670                                                      std::vector<SDValue>&Ops,
25671                                                      SelectionDAG &DAG) const {
25672   SDValue Result;
25673
25674   // Only support length 1 constraints for now.
25675   if (Constraint.length() > 1) return;
25676
25677   char ConstraintLetter = Constraint[0];
25678   switch (ConstraintLetter) {
25679   default: break;
25680   case 'I':
25681     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25682       if (C->getZExtValue() <= 31) {
25683         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25684                                        Op.getValueType());
25685         break;
25686       }
25687     }
25688     return;
25689   case 'J':
25690     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25691       if (C->getZExtValue() <= 63) {
25692         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25693                                        Op.getValueType());
25694         break;
25695       }
25696     }
25697     return;
25698   case 'K':
25699     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25700       if (isInt<8>(C->getSExtValue())) {
25701         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25702                                        Op.getValueType());
25703         break;
25704       }
25705     }
25706     return;
25707   case 'L':
25708     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25709       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25710           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25711         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25712                                        Op.getValueType());
25713         break;
25714       }
25715     }
25716     return;
25717   case 'M':
25718     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25719       if (C->getZExtValue() <= 3) {
25720         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25721                                        Op.getValueType());
25722         break;
25723       }
25724     }
25725     return;
25726   case 'N':
25727     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25728       if (C->getZExtValue() <= 255) {
25729         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25730                                        Op.getValueType());
25731         break;
25732       }
25733     }
25734     return;
25735   case 'O':
25736     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25737       if (C->getZExtValue() <= 127) {
25738         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25739                                        Op.getValueType());
25740         break;
25741       }
25742     }
25743     return;
25744   case 'e': {
25745     // 32-bit signed value
25746     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25747       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25748                                            C->getSExtValue())) {
25749         // Widen to 64 bits here to get it sign extended.
25750         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25751         break;
25752       }
25753     // FIXME gcc accepts some relocatable values here too, but only in certain
25754     // memory models; it's complicated.
25755     }
25756     return;
25757   }
25758   case 'Z': {
25759     // 32-bit unsigned value
25760     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25761       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25762                                            C->getZExtValue())) {
25763         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25764                                        Op.getValueType());
25765         break;
25766       }
25767     }
25768     // FIXME gcc accepts some relocatable values here too, but only in certain
25769     // memory models; it's complicated.
25770     return;
25771   }
25772   case 'i': {
25773     // Literal immediates are always ok.
25774     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25775       // Widen to 64 bits here to get it sign extended.
25776       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25777       break;
25778     }
25779
25780     // In any sort of PIC mode addresses need to be computed at runtime by
25781     // adding in a register or some sort of table lookup.  These can't
25782     // be used as immediates.
25783     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25784       return;
25785
25786     // If we are in non-pic codegen mode, we allow the address of a global (with
25787     // an optional displacement) to be used with 'i'.
25788     GlobalAddressSDNode *GA = nullptr;
25789     int64_t Offset = 0;
25790
25791     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25792     while (1) {
25793       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25794         Offset += GA->getOffset();
25795         break;
25796       } else if (Op.getOpcode() == ISD::ADD) {
25797         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25798           Offset += C->getZExtValue();
25799           Op = Op.getOperand(0);
25800           continue;
25801         }
25802       } else if (Op.getOpcode() == ISD::SUB) {
25803         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25804           Offset += -C->getZExtValue();
25805           Op = Op.getOperand(0);
25806           continue;
25807         }
25808       }
25809
25810       // Otherwise, this isn't something we can handle, reject it.
25811       return;
25812     }
25813
25814     const GlobalValue *GV = GA->getGlobal();
25815     // If we require an extra load to get this address, as in PIC mode, we
25816     // can't accept it.
25817     if (isGlobalStubReference(
25818             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25819       return;
25820
25821     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25822                                         GA->getValueType(0), Offset);
25823     break;
25824   }
25825   }
25826
25827   if (Result.getNode()) {
25828     Ops.push_back(Result);
25829     return;
25830   }
25831   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25832 }
25833
25834 std::pair<unsigned, const TargetRegisterClass *>
25835 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25836                                                 StringRef Constraint,
25837                                                 MVT VT) const {
25838   // First, see if this is a constraint that directly corresponds to an LLVM
25839   // register class.
25840   if (Constraint.size() == 1) {
25841     // GCC Constraint Letters
25842     switch (Constraint[0]) {
25843     default: break;
25844       // TODO: Slight differences here in allocation order and leaving
25845       // RIP in the class. Do they matter any more here than they do
25846       // in the normal allocation?
25847     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25848       if (Subtarget->is64Bit()) {
25849         if (VT == MVT::i32 || VT == MVT::f32)
25850           return std::make_pair(0U, &X86::GR32RegClass);
25851         if (VT == MVT::i16)
25852           return std::make_pair(0U, &X86::GR16RegClass);
25853         if (VT == MVT::i8 || VT == MVT::i1)
25854           return std::make_pair(0U, &X86::GR8RegClass);
25855         if (VT == MVT::i64 || VT == MVT::f64)
25856           return std::make_pair(0U, &X86::GR64RegClass);
25857         break;
25858       }
25859       // 32-bit fallthrough
25860     case 'Q':   // Q_REGS
25861       if (VT == MVT::i32 || VT == MVT::f32)
25862         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25863       if (VT == MVT::i16)
25864         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25865       if (VT == MVT::i8 || VT == MVT::i1)
25866         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25867       if (VT == MVT::i64)
25868         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25869       break;
25870     case 'r':   // GENERAL_REGS
25871     case 'l':   // INDEX_REGS
25872       if (VT == MVT::i8 || VT == MVT::i1)
25873         return std::make_pair(0U, &X86::GR8RegClass);
25874       if (VT == MVT::i16)
25875         return std::make_pair(0U, &X86::GR16RegClass);
25876       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25877         return std::make_pair(0U, &X86::GR32RegClass);
25878       return std::make_pair(0U, &X86::GR64RegClass);
25879     case 'R':   // LEGACY_REGS
25880       if (VT == MVT::i8 || VT == MVT::i1)
25881         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25882       if (VT == MVT::i16)
25883         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25884       if (VT == MVT::i32 || !Subtarget->is64Bit())
25885         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25886       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25887     case 'f':  // FP Stack registers.
25888       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25889       // value to the correct fpstack register class.
25890       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25891         return std::make_pair(0U, &X86::RFP32RegClass);
25892       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25893         return std::make_pair(0U, &X86::RFP64RegClass);
25894       return std::make_pair(0U, &X86::RFP80RegClass);
25895     case 'y':   // MMX_REGS if MMX allowed.
25896       if (!Subtarget->hasMMX()) break;
25897       return std::make_pair(0U, &X86::VR64RegClass);
25898     case 'Y':   // SSE_REGS if SSE2 allowed
25899       if (!Subtarget->hasSSE2()) break;
25900       // FALL THROUGH.
25901     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25902       if (!Subtarget->hasSSE1()) break;
25903
25904       switch (VT.SimpleTy) {
25905       default: break;
25906       // Scalar SSE types.
25907       case MVT::f32:
25908       case MVT::i32:
25909         return std::make_pair(0U, &X86::FR32RegClass);
25910       case MVT::f64:
25911       case MVT::i64:
25912         return std::make_pair(0U, &X86::FR64RegClass);
25913       // Vector types.
25914       case MVT::v16i8:
25915       case MVT::v8i16:
25916       case MVT::v4i32:
25917       case MVT::v2i64:
25918       case MVT::v4f32:
25919       case MVT::v2f64:
25920         return std::make_pair(0U, &X86::VR128RegClass);
25921       // AVX types.
25922       case MVT::v32i8:
25923       case MVT::v16i16:
25924       case MVT::v8i32:
25925       case MVT::v4i64:
25926       case MVT::v8f32:
25927       case MVT::v4f64:
25928         return std::make_pair(0U, &X86::VR256RegClass);
25929       case MVT::v8f64:
25930       case MVT::v16f32:
25931       case MVT::v16i32:
25932       case MVT::v8i64:
25933         return std::make_pair(0U, &X86::VR512RegClass);
25934       }
25935       break;
25936     }
25937   }
25938
25939   // Use the default implementation in TargetLowering to convert the register
25940   // constraint into a member of a register class.
25941   std::pair<unsigned, const TargetRegisterClass*> Res;
25942   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25943
25944   // Not found as a standard register?
25945   if (!Res.second) {
25946     // Map st(0) -> st(7) -> ST0
25947     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25948         tolower(Constraint[1]) == 's' &&
25949         tolower(Constraint[2]) == 't' &&
25950         Constraint[3] == '(' &&
25951         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25952         Constraint[5] == ')' &&
25953         Constraint[6] == '}') {
25954
25955       Res.first = X86::FP0+Constraint[4]-'0';
25956       Res.second = &X86::RFP80RegClass;
25957       return Res;
25958     }
25959
25960     // GCC allows "st(0)" to be called just plain "st".
25961     if (StringRef("{st}").equals_lower(Constraint)) {
25962       Res.first = X86::FP0;
25963       Res.second = &X86::RFP80RegClass;
25964       return Res;
25965     }
25966
25967     // flags -> EFLAGS
25968     if (StringRef("{flags}").equals_lower(Constraint)) {
25969       Res.first = X86::EFLAGS;
25970       Res.second = &X86::CCRRegClass;
25971       return Res;
25972     }
25973
25974     // 'A' means EAX + EDX.
25975     if (Constraint == "A") {
25976       Res.first = X86::EAX;
25977       Res.second = &X86::GR32_ADRegClass;
25978       return Res;
25979     }
25980     return Res;
25981   }
25982
25983   // Otherwise, check to see if this is a register class of the wrong value
25984   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25985   // turn into {ax},{dx}.
25986   // MVT::Other is used to specify clobber names.
25987   if (Res.second->hasType(VT) || VT == MVT::Other)
25988     return Res;   // Correct type already, nothing to do.
25989
25990   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
25991   // return "eax". This should even work for things like getting 64bit integer
25992   // registers when given an f64 type.
25993   const TargetRegisterClass *Class = Res.second;
25994   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
25995       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
25996     unsigned Size = VT.getSizeInBits();
25997     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
25998                                   : Size == 16 ? MVT::i16
25999                                   : Size == 32 ? MVT::i32
26000                                   : Size == 64 ? MVT::i64
26001                                   : MVT::Other;
26002     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26003     if (DestReg > 0) {
26004       Res.first = DestReg;
26005       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26006                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26007                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26008                  : &X86::GR64RegClass;
26009       assert(Res.second->contains(Res.first) && "Register in register class");
26010     } else {
26011       // No register found/type mismatch.
26012       Res.first = 0;
26013       Res.second = nullptr;
26014     }
26015   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26016              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26017              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26018              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26019              Class == &X86::VR512RegClass) {
26020     // Handle references to XMM physical registers that got mapped into the
26021     // wrong class.  This can happen with constraints like {xmm0} where the
26022     // target independent register mapper will just pick the first match it can
26023     // find, ignoring the required type.
26024
26025     if (VT == MVT::f32 || VT == MVT::i32)
26026       Res.second = &X86::FR32RegClass;
26027     else if (VT == MVT::f64 || VT == MVT::i64)
26028       Res.second = &X86::FR64RegClass;
26029     else if (X86::VR128RegClass.hasType(VT))
26030       Res.second = &X86::VR128RegClass;
26031     else if (X86::VR256RegClass.hasType(VT))
26032       Res.second = &X86::VR256RegClass;
26033     else if (X86::VR512RegClass.hasType(VT))
26034       Res.second = &X86::VR512RegClass;
26035     else {
26036       // Type mismatch and not a clobber: Return an error;
26037       Res.first = 0;
26038       Res.second = nullptr;
26039     }
26040   }
26041
26042   return Res;
26043 }
26044
26045 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26046                                             Type *Ty,
26047                                             unsigned AS) const {
26048   // Scaling factors are not free at all.
26049   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26050   // will take 2 allocations in the out of order engine instead of 1
26051   // for plain addressing mode, i.e. inst (reg1).
26052   // E.g.,
26053   // vaddps (%rsi,%drx), %ymm0, %ymm1
26054   // Requires two allocations (one for the load, one for the computation)
26055   // whereas:
26056   // vaddps (%rsi), %ymm0, %ymm1
26057   // Requires just 1 allocation, i.e., freeing allocations for other operations
26058   // and having less micro operations to execute.
26059   //
26060   // For some X86 architectures, this is even worse because for instance for
26061   // stores, the complex addressing mode forces the instruction to use the
26062   // "load" ports instead of the dedicated "store" port.
26063   // E.g., on Haswell:
26064   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26065   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26066   if (isLegalAddressingMode(AM, Ty, AS))
26067     // Scale represents reg2 * scale, thus account for 1
26068     // as soon as we use a second register.
26069     return AM.Scale != 0;
26070   return -1;
26071 }
26072
26073 bool X86TargetLowering::isTargetFTOL() const {
26074   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26075 }