[X86][SSE] Use the general SMAX/SMIN/UMAX/UMIN pattern matching and remove the X86...
[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 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71                                      const X86Subtarget &STI)
72     : TargetLowering(TM), Subtarget(&STI) {
73   X86ScalarSSEf64 = Subtarget->hasSSE2();
74   X86ScalarSSEf32 = Subtarget->hasSSE1();
75   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
76
77   // Set up the TargetLowering object.
78   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
79
80   // X86 is weird. It always uses i8 for shift amounts and setcc results.
81   setBooleanContents(ZeroOrOneBooleanContent);
82   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84
85   // For 64-bit, since we have so many registers, use the ILP scheduler.
86   // For 32-bit, use the register pressure specific scheduling.
87   // For Atom, always use ILP scheduling.
88   if (Subtarget->isAtom())
89     setSchedulingPreference(Sched::ILP);
90   else if (Subtarget->is64Bit())
91     setSchedulingPreference(Sched::ILP);
92   else
93     setSchedulingPreference(Sched::RegPressure);
94   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
96
97   // Bypass expensive divides on Atom when compiling with O2.
98   if (TM.getOptLevel() >= CodeGenOpt::Default) {
99     if (Subtarget->hasSlowDivide32())
100       addBypassSlowDiv(32, 8);
101     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102       addBypassSlowDiv(64, 16);
103   }
104
105   if (Subtarget->isTargetKnownWindowsMSVC()) {
106     // Setup Windows compiler runtime calls.
107     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109     setLibcallName(RTLIB::SREM_I64, "_allrem");
110     setLibcallName(RTLIB::UREM_I64, "_aullrem");
111     setLibcallName(RTLIB::MUL_I64, "_allmul");
112     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
117
118     // The _ftol2 runtime function has an unusual calling conv, which
119     // is modeled by a special pseudo-instruction.
120     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
121     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
122     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
123     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
124   }
125
126   if (Subtarget->isTargetDarwin()) {
127     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
128     setUseUnderscoreSetJmp(false);
129     setUseUnderscoreLongJmp(false);
130   } else if (Subtarget->isTargetWindowsGNU()) {
131     // MS runtime is weird: it exports _setjmp, but longjmp!
132     setUseUnderscoreSetJmp(true);
133     setUseUnderscoreLongJmp(false);
134   } else {
135     setUseUnderscoreSetJmp(true);
136     setUseUnderscoreLongJmp(true);
137   }
138
139   // Set up the register classes.
140   addRegisterClass(MVT::i8, &X86::GR8RegClass);
141   addRegisterClass(MVT::i16, &X86::GR16RegClass);
142   addRegisterClass(MVT::i32, &X86::GR32RegClass);
143   if (Subtarget->is64Bit())
144     addRegisterClass(MVT::i64, &X86::GR64RegClass);
145
146   for (MVT VT : MVT::integer_valuetypes())
147     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
148
149   // We don't accept any truncstore of integer registers.
150   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
151   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
152   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
153   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
154   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
155   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
156
157   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
158
159   // SETOEQ and SETUNE require checking two conditions.
160   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
161   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
162   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
163   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
164   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
165   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
166
167   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
168   // operation.
169   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
170   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
171   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
172
173   if (Subtarget->is64Bit()) {
174     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
175     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
176   } else if (!Subtarget->useSoftFloat()) {
177     // We have an algorithm for SSE2->double, and we turn this into a
178     // 64-bit FILD followed by conditional FADD for other targets.
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180     // We have an algorithm for SSE2, and we turn this into a 64-bit
181     // FILD for other targets.
182     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
183   }
184
185   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
186   // this operation.
187   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
188   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
189
190   if (!Subtarget->useSoftFloat()) {
191     // SSE has no i16 to fp conversion, only i32
192     if (X86ScalarSSEf32) {
193       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
194       // f32 and f64 cases are Legal, f80 case is not
195       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
196     } else {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
198       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
199     }
200   } else {
201     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
202     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
203   }
204
205   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
206   // are Legal, f80 is custom lowered.
207   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
208   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
209
210   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
211   // this operation.
212   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
213   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
214
215   if (X86ScalarSSEf32) {
216     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
217     // f32 and f64 cases are Legal, f80 case is not
218     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
219   } else {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
221     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
222   }
223
224   // Handle FP_TO_UINT by promoting the destination to a larger signed
225   // conversion.
226   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
227   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
228   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
229
230   if (Subtarget->is64Bit()) {
231     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
232     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
233   } else if (!Subtarget->useSoftFloat()) {
234     // Since AVX is a superset of SSE3, only check for SSE here.
235     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
236       // Expand FP_TO_UINT into a select.
237       // FIXME: We would like to use a Custom expander here eventually to do
238       // the optimal thing for SSE vs. the default expansion in the legalizer.
239       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
240     else
241       // With SSE3 we can use fisttpll to convert to a signed i64; without
242       // SSE, we're stuck with a fistpll.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
244   }
245
246   if (isTargetFTOL()) {
247     // Use the _ftol2 runtime function, which has a pseudo-instruction
248     // to handle its weird calling convention.
249     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
250   }
251
252   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253   if (!X86ScalarSSEf64) {
254     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
255     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
256     if (Subtarget->is64Bit()) {
257       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
258       // Without SSE, i64->f64 goes through memory.
259       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
260     }
261   }
262
263   // Scalar integer divide and remainder are lowered to use operations that
264   // produce two results, to match the available instructions. This exposes
265   // the two-result form to trivial CSE, which is able to combine x/y and x%y
266   // into a single instruction.
267   //
268   // Scalar integer multiply-high is also lowered to use two-result
269   // operations, to match the available instructions. However, plain multiply
270   // (low) operations are left as Legal, as there are single-result
271   // instructions for this in x86. Using the two-result multiply instructions
272   // when both high and low results are needed must be arranged by dagcombine.
273   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
274     MVT VT = IntVTs[i];
275     setOperationAction(ISD::MULHS, VT, Expand);
276     setOperationAction(ISD::MULHU, VT, Expand);
277     setOperationAction(ISD::SDIV, VT, Expand);
278     setOperationAction(ISD::UDIV, VT, Expand);
279     setOperationAction(ISD::SREM, VT, Expand);
280     setOperationAction(ISD::UREM, VT, Expand);
281
282     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283     setOperationAction(ISD::ADDC, VT, Custom);
284     setOperationAction(ISD::ADDE, VT, Custom);
285     setOperationAction(ISD::SUBC, VT, Custom);
286     setOperationAction(ISD::SUBE, VT, Custom);
287   }
288
289   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
290   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
291   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
292   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
293   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
294   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
295   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
298   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
299   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
300   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
301   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
305   if (Subtarget->is64Bit())
306     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
308   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
309   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
310   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
311   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
312   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
313   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
314   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
315
316   // Promote the i8 variants and force them on up to i32 which has a shorter
317   // encoding.
318   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
319   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
320   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
321   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
322   if (Subtarget->hasBMI()) {
323     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
324     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
325     if (Subtarget->is64Bit())
326       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
327   } else {
328     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
329     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
330     if (Subtarget->is64Bit())
331       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
332   }
333
334   if (Subtarget->hasLZCNT()) {
335     // When promoting the i8 variants, force them to i32 for a shorter
336     // encoding.
337     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
338     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
339     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
340     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
341     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
342     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
343     if (Subtarget->is64Bit())
344       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
345   } else {
346     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
347     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
348     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
349     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
350     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
351     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
352     if (Subtarget->is64Bit()) {
353       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
354       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
355     }
356   }
357
358   // Special handling for half-precision floating point conversions.
359   // If we don't have F16C support, then lower half float conversions
360   // into library calls.
361   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
362     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
363     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
364   }
365
366   // There's never any support for operations beyond MVT::f32.
367   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
368   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
369   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
370   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
371
372   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
373   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
374   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
375   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
376   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
377   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
378
379   if (Subtarget->hasPOPCNT()) {
380     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
381   } else {
382     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
383     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
384     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
385     if (Subtarget->is64Bit())
386       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
387   }
388
389   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
390
391   if (!Subtarget->hasMOVBE())
392     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
393
394   // These should be promoted to a larger select which is supported.
395   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
396   // X86 wants to expand cmov itself.
397   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
398   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
399   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
400   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
401   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
402   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
403   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
404   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
405   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
406   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
408   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
409   if (Subtarget->is64Bit()) {
410     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
411     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
412   }
413   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
414   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
415   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
416   // support continuation, user-level threading, and etc.. As a result, no
417   // other SjLj exception interfaces are implemented and please don't build
418   // your own exception handling based on them.
419   // LLVM/Clang supports zero-cost DWARF exception handling.
420   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
421   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
422
423   // Darwin ABI issue.
424   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
425   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
426   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
427   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
428   if (Subtarget->is64Bit())
429     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
430   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
431   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
432   if (Subtarget->is64Bit()) {
433     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
434     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
435     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
436     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
437     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
438   }
439   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
440   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
441   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
442   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
443   if (Subtarget->is64Bit()) {
444     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
445     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
446     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
447   }
448
449   if (Subtarget->hasSSE1())
450     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
451
452   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
453
454   // Expand certain atomics
455   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
456     MVT VT = IntVTs[i];
457     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
458     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
459     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
460   }
461
462   if (Subtarget->hasCmpxchg16b()) {
463     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
464   }
465
466   // FIXME - use subtarget debug flags
467   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
468       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
469     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
470   }
471
472   if (Subtarget->is64Bit()) {
473     setExceptionPointerRegister(X86::RAX);
474     setExceptionSelectorRegister(X86::RDX);
475   } else {
476     setExceptionPointerRegister(X86::EAX);
477     setExceptionSelectorRegister(X86::EDX);
478   }
479   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
480   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
481
482   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
483   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
484
485   setOperationAction(ISD::TRAP, MVT::Other, Legal);
486   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
487
488   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
489   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
490   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
491   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
492     // TargetInfo::X86_64ABIBuiltinVaList
493     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
494     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
495   } else {
496     // TargetInfo::CharPtrBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
499   }
500
501   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
502   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
503
504   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
505
506   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
507   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
508   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
509
510   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
511     // f32 and f64 use SSE.
512     // Set up the FP register classes.
513     addRegisterClass(MVT::f32, &X86::FR32RegClass);
514     addRegisterClass(MVT::f64, &X86::FR64RegClass);
515
516     // Use ANDPD to simulate FABS.
517     setOperationAction(ISD::FABS , MVT::f64, Custom);
518     setOperationAction(ISD::FABS , MVT::f32, Custom);
519
520     // Use XORP to simulate FNEG.
521     setOperationAction(ISD::FNEG , MVT::f64, Custom);
522     setOperationAction(ISD::FNEG , MVT::f32, Custom);
523
524     // Use ANDPD and ORPD to simulate FCOPYSIGN.
525     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
526     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
527
528     // Lower this to FGETSIGNx86 plus an AND.
529     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
530     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
531
532     // We don't support sin/cos/fmod
533     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
534     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
535     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
536     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
537     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
538     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
539
540     // Expand FP immediates into loads from the stack, except for the special
541     // cases we handle.
542     addLegalFPImmediate(APFloat(+0.0)); // xorpd
543     addLegalFPImmediate(APFloat(+0.0f)); // xorps
544   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
545     // Use SSE for f32, x87 for f64.
546     // Set up the FP register classes.
547     addRegisterClass(MVT::f32, &X86::FR32RegClass);
548     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
549
550     // Use ANDPS to simulate FABS.
551     setOperationAction(ISD::FABS , MVT::f32, Custom);
552
553     // Use XORP to simulate FNEG.
554     setOperationAction(ISD::FNEG , MVT::f32, Custom);
555
556     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
557
558     // Use ANDPS and ORPS to simulate FCOPYSIGN.
559     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
560     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
561
562     // We don't support sin/cos/fmod
563     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
564     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
565     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
566
567     // Special cases we handle for FP constants.
568     addLegalFPImmediate(APFloat(+0.0f)); // xorps
569     addLegalFPImmediate(APFloat(+0.0)); // FLD0
570     addLegalFPImmediate(APFloat(+1.0)); // FLD1
571     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
572     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
573
574     if (!TM.Options.UnsafeFPMath) {
575       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
576       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
577       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
578     }
579   } else if (!Subtarget->useSoftFloat()) {
580     // f32 and f64 in x87.
581     // Set up the FP register classes.
582     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
583     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
584
585     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
586     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
587     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
588     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
589
590     if (!TM.Options.UnsafeFPMath) {
591       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
592       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
593       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
594       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
595       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
596       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
597     }
598     addLegalFPImmediate(APFloat(+0.0)); // FLD0
599     addLegalFPImmediate(APFloat(+1.0)); // FLD1
600     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
606   }
607
608   // We don't support FMA.
609   setOperationAction(ISD::FMA, MVT::f64, Expand);
610   setOperationAction(ISD::FMA, MVT::f32, Expand);
611
612   // Long double always uses X87.
613   if (!Subtarget->useSoftFloat()) {
614     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
615     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
616     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
617     {
618       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
619       addLegalFPImmediate(TmpFlt);  // FLD0
620       TmpFlt.changeSign();
621       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
622
623       bool ignored;
624       APFloat TmpFlt2(+1.0);
625       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
626                       &ignored);
627       addLegalFPImmediate(TmpFlt2);  // FLD1
628       TmpFlt2.changeSign();
629       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
630     }
631
632     if (!TM.Options.UnsafeFPMath) {
633       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
634       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
635       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
636     }
637
638     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
639     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
640     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
641     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
642     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
643     setOperationAction(ISD::FMA, MVT::f80, Expand);
644   }
645
646   // Always use a library call for pow.
647   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
648   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
649   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
650
651   setOperationAction(ISD::FLOG, MVT::f80, Expand);
652   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
653   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
654   setOperationAction(ISD::FEXP, MVT::f80, Expand);
655   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
656   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
657   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
658
659   // First set operation action for all vector types to either promote
660   // (for widening) or expand (for scalarization). Then we will selectively
661   // turn on ones that can be effectively codegen'd.
662   for (MVT VT : MVT::vector_valuetypes()) {
663     setOperationAction(ISD::ADD , VT, Expand);
664     setOperationAction(ISD::SUB , VT, Expand);
665     setOperationAction(ISD::FADD, VT, Expand);
666     setOperationAction(ISD::FNEG, VT, Expand);
667     setOperationAction(ISD::FSUB, VT, Expand);
668     setOperationAction(ISD::MUL , VT, Expand);
669     setOperationAction(ISD::FMUL, VT, Expand);
670     setOperationAction(ISD::SDIV, VT, Expand);
671     setOperationAction(ISD::UDIV, VT, Expand);
672     setOperationAction(ISD::FDIV, VT, Expand);
673     setOperationAction(ISD::SREM, VT, Expand);
674     setOperationAction(ISD::UREM, VT, Expand);
675     setOperationAction(ISD::LOAD, VT, Expand);
676     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
677     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
678     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
679     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
680     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
681     setOperationAction(ISD::FABS, VT, Expand);
682     setOperationAction(ISD::FSIN, VT, Expand);
683     setOperationAction(ISD::FSINCOS, VT, Expand);
684     setOperationAction(ISD::FCOS, VT, Expand);
685     setOperationAction(ISD::FSINCOS, VT, Expand);
686     setOperationAction(ISD::FREM, VT, Expand);
687     setOperationAction(ISD::FMA,  VT, Expand);
688     setOperationAction(ISD::FPOWI, VT, Expand);
689     setOperationAction(ISD::FSQRT, VT, Expand);
690     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
691     setOperationAction(ISD::FFLOOR, VT, Expand);
692     setOperationAction(ISD::FCEIL, VT, Expand);
693     setOperationAction(ISD::FTRUNC, VT, Expand);
694     setOperationAction(ISD::FRINT, VT, Expand);
695     setOperationAction(ISD::FNEARBYINT, VT, Expand);
696     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
697     setOperationAction(ISD::MULHS, VT, Expand);
698     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
699     setOperationAction(ISD::MULHU, VT, Expand);
700     setOperationAction(ISD::SDIVREM, VT, Expand);
701     setOperationAction(ISD::UDIVREM, VT, Expand);
702     setOperationAction(ISD::FPOW, VT, Expand);
703     setOperationAction(ISD::CTPOP, VT, Expand);
704     setOperationAction(ISD::CTTZ, VT, Expand);
705     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
706     setOperationAction(ISD::CTLZ, VT, Expand);
707     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
708     setOperationAction(ISD::SHL, VT, Expand);
709     setOperationAction(ISD::SRA, VT, Expand);
710     setOperationAction(ISD::SRL, VT, Expand);
711     setOperationAction(ISD::ROTL, VT, Expand);
712     setOperationAction(ISD::ROTR, VT, Expand);
713     setOperationAction(ISD::BSWAP, VT, Expand);
714     setOperationAction(ISD::SETCC, VT, Expand);
715     setOperationAction(ISD::FLOG, VT, Expand);
716     setOperationAction(ISD::FLOG2, VT, Expand);
717     setOperationAction(ISD::FLOG10, VT, Expand);
718     setOperationAction(ISD::FEXP, VT, Expand);
719     setOperationAction(ISD::FEXP2, VT, Expand);
720     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
721     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
722     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
723     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
724     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
725     setOperationAction(ISD::TRUNCATE, VT, Expand);
726     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
727     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
728     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
729     setOperationAction(ISD::VSELECT, VT, Expand);
730     setOperationAction(ISD::SELECT_CC, VT, Expand);
731     for (MVT InnerVT : MVT::vector_valuetypes()) {
732       setTruncStoreAction(InnerVT, VT, Expand);
733
734       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
736
737       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738       // types, we have to deal with them whether we ask for Expansion or not.
739       // Setting Expand causes its own optimisation problems though, so leave
740       // them legal.
741       if (VT.getVectorElementType() == MVT::i1)
742         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
743
744       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745       // split/scalarized right now.
746       if (VT.getVectorElementType() == MVT::f16)
747         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748     }
749   }
750
751   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752   // with -msoft-float, disable use of MMX as well.
753   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
754     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755     // No operations on x86mmx supported, everything uses intrinsics.
756   }
757
758   // MMX-sized vectors (other than x86mmx) are expected to be expanded
759   // into smaller operations.
760   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
761     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
762     setOperationAction(ISD::AND,                MMXTy,      Expand);
763     setOperationAction(ISD::OR,                 MMXTy,      Expand);
764     setOperationAction(ISD::XOR,                MMXTy,      Expand);
765     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
766     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
767     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
768   }
769   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
770
771   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
772     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
773
774     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
775     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
776     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
777     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
778     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
779     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
780     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
781     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
782     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
783     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
784     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
785     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
786     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
787     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
788   }
789
790   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
791     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
792
793     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
794     // registers cannot be used even for integer operations.
795     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
796     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
797     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
798     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
799
800     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
801     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
802     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
803     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
804     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
805     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
806     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
807     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
808     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
809     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
810     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
811     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
812     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
813     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
814     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
815     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
816     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
817     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
818     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
819     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
820     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
821     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
822     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
823
824     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
825     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
826     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
827     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
828
829     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
830     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
831     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
832     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
833
834     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
839
840     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
841     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
842     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
843     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
844
845     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
846     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
847       MVT VT = (MVT::SimpleValueType)i;
848       // Do not attempt to custom lower non-power-of-2 vectors
849       if (!isPowerOf2_32(VT.getVectorNumElements()))
850         continue;
851       // Do not attempt to custom lower non-128-bit vectors
852       if (!VT.is128BitVector())
853         continue;
854       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
855       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
856       setOperationAction(ISD::VSELECT,            VT, Custom);
857       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
858     }
859
860     // We support custom legalizing of sext and anyext loads for specific
861     // memory vector types which we can load as a scalar (or sequence of
862     // scalars) and extend in-register to a legal 128-bit vector type. For sext
863     // loads these must work with a single scalar load.
864     for (MVT VT : MVT::integer_vector_valuetypes()) {
865       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
866       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
867       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
868       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
869       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
870       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
871       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
874     }
875
876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
877     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
878     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
879     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
880     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
881     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
882     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
883     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
884
885     if (Subtarget->is64Bit()) {
886       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
887       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
888     }
889
890     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
891     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
892       MVT VT = (MVT::SimpleValueType)i;
893
894       // Do not attempt to promote non-128-bit vectors
895       if (!VT.is128BitVector())
896         continue;
897
898       setOperationAction(ISD::AND,    VT, Promote);
899       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
900       setOperationAction(ISD::OR,     VT, Promote);
901       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
902       setOperationAction(ISD::XOR,    VT, Promote);
903       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
904       setOperationAction(ISD::LOAD,   VT, Promote);
905       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
906       setOperationAction(ISD::SELECT, VT, Promote);
907       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
908     }
909
910     // Custom lower v2i64 and v2f64 selects.
911     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
912     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
913     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
914     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
915
916     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
917     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
918
919     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
920
921     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
922     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
923     // As there is no 64-bit GPR available, we need build a special custom
924     // sequence to convert from v2i32 to v2f32.
925     if (!Subtarget->is64Bit())
926       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
927
928     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
929     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
930
931     for (MVT VT : MVT::fp_vector_valuetypes())
932       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
933
934     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
935     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
936     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
937   }
938
939   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
940     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
941       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
942       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
943       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
944       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
945       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
946     }
947
948     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
949     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
950     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
951     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
952     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
956
957     // FIXME: Do we need to handle scalar-to-vector here?
958     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
959
960     // We directly match byte blends in the backend as they match the VSELECT
961     // condition form.
962     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
963
964     // SSE41 brings specific instructions for doing vector sign extend even in
965     // cases where we don't have SRA.
966     for (MVT VT : MVT::integer_vector_valuetypes()) {
967       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
968       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
969       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
970     }
971
972     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
973     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
974     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
975     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
976     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
979
980     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
981     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
982     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
983     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
986
987     // i8 and i16 vectors are custom because the source register and source
988     // source memory operand types are not the same width.  f32 vectors are
989     // custom since the immediate controlling the insert encodes additional
990     // information.
991     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
992     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
993     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
994     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
995
996     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
997     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
999     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1000
1001     // FIXME: these should be Legal, but that's only for the case where
1002     // the index is constant.  For now custom expand to deal with that.
1003     if (Subtarget->is64Bit()) {
1004       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1005       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1006     }
1007   }
1008
1009   if (Subtarget->hasSSE2()) {
1010     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1011     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1012     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1013
1014     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1015     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1016
1017     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1018     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1019
1020     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1021     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1022
1023     // In the customized shift lowering, the legal cases in AVX2 will be
1024     // recognized.
1025     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1026     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1027
1028     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1029     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1030
1031     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1032     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1033   }
1034
1035   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1036     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1037     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1039     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1040     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1042
1043     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1044     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1045     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1046
1047     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1049     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1050     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1052     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1057     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1058     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1059
1060     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1061     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1062     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1063     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1064     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1065     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1068     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1070     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1071     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1072
1073     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1074     // even though v8i16 is a legal type.
1075     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1076     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1077     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1078
1079     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1082
1083     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1084     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1085
1086     for (MVT VT : MVT::fp_vector_valuetypes())
1087       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1088
1089     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1090     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1091
1092     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1093     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1094
1095     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1096     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1097
1098     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1099     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1100     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1101     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1102
1103     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1104     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1105     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1106
1107     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1108     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1109     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1110     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1111     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1112     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1113     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1114     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1115     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1116     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1117     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1118     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1119
1120     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1121     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1122     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1123     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1124
1125     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1126       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1127       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1128       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1129       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1130       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1132     }
1133
1134     if (Subtarget->hasInt256()) {
1135       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1136       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1137       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1138       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1139
1140       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1141       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1142       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1143       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1144
1145       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1146       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1147       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1148       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1149
1150       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1151       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1152       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1153       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1154
1155       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1156       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1157       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1158       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1159       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1160       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1161       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1162       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1163       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1164       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1165       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1166       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1167
1168       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1169       // when we have a 256bit-wide blend with immediate.
1170       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1171
1172       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1173       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1174       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1175       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1176       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1179
1180       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1182       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1183       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1186     } else {
1187       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1188       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1189       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1190       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1191
1192       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1193       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1194       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1195       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1196
1197       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1198       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1199       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1200       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1201
1202       setOperationAction(ISD::SMAX,            MVT::v32i8,  Custom);
1203       setOperationAction(ISD::SMAX,            MVT::v16i16, Custom);
1204       setOperationAction(ISD::SMAX,            MVT::v8i32,  Custom);
1205       setOperationAction(ISD::UMAX,            MVT::v32i8,  Custom);
1206       setOperationAction(ISD::UMAX,            MVT::v16i16, Custom);
1207       setOperationAction(ISD::UMAX,            MVT::v8i32,  Custom);
1208       setOperationAction(ISD::SMIN,            MVT::v32i8,  Custom);
1209       setOperationAction(ISD::SMIN,            MVT::v16i16, Custom);
1210       setOperationAction(ISD::SMIN,            MVT::v8i32,  Custom);
1211       setOperationAction(ISD::UMIN,            MVT::v32i8,  Custom);
1212       setOperationAction(ISD::UMIN,            MVT::v16i16, Custom);
1213       setOperationAction(ISD::UMIN,            MVT::v8i32,  Custom);
1214     }
1215
1216     // In the customized shift lowering, the legal cases in AVX2 will be
1217     // recognized.
1218     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1219     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1220
1221     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1222     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1223
1224     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1225     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1226
1227     // Custom lower several nodes for 256-bit types.
1228     for (MVT VT : MVT::vector_valuetypes()) {
1229       if (VT.getScalarSizeInBits() >= 32) {
1230         setOperationAction(ISD::MLOAD,  VT, Legal);
1231         setOperationAction(ISD::MSTORE, VT, Legal);
1232       }
1233       // Extract subvector is special because the value type
1234       // (result) is 128-bit but the source is 256-bit wide.
1235       if (VT.is128BitVector()) {
1236         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1237       }
1238       // Do not attempt to custom lower other non-256-bit vectors
1239       if (!VT.is256BitVector())
1240         continue;
1241
1242       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1243       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1244       setOperationAction(ISD::VSELECT,            VT, Custom);
1245       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1246       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1247       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1248       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1249       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1250     }
1251
1252     if (Subtarget->hasInt256())
1253       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1254
1255
1256     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1257     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1258       MVT VT = (MVT::SimpleValueType)i;
1259
1260       // Do not attempt to promote non-256-bit vectors
1261       if (!VT.is256BitVector())
1262         continue;
1263
1264       setOperationAction(ISD::AND,    VT, Promote);
1265       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1266       setOperationAction(ISD::OR,     VT, Promote);
1267       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1268       setOperationAction(ISD::XOR,    VT, Promote);
1269       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1270       setOperationAction(ISD::LOAD,   VT, Promote);
1271       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1272       setOperationAction(ISD::SELECT, VT, Promote);
1273       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1274     }
1275   }
1276
1277   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1278     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1279     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1280     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1281     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1282
1283     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1284     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1285     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1286
1287     for (MVT VT : MVT::fp_vector_valuetypes())
1288       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1289
1290     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1291     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1292     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1293     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1294     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1295     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1296     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1297     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1298     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1299     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1300     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1301     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1302
1303     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1304     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1305     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1306     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1307     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1308     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1309     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1310     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1311     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1314     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1315     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1316
1317     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1321     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1322     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1323
1324     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1328     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1329     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1330     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1331     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1332
1333     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1334     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1335     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1336     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1337     if (Subtarget->is64Bit()) {
1338       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1339       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1340       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1341       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1342     }
1343     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1345     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1346     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1347     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1348     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1349     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1350     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1351     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1352     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1353     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1354     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1356     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1357     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1358     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1359
1360     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1361     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1362     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1363     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1364     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1365     if (Subtarget->hasVLX()){
1366       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1367       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1368       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1369       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1370       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1371
1372       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1373       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1374       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1375       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1376       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1377     }
1378     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1379     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1380     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1381     if (Subtarget->hasDQI()) {
1382       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1383       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1384
1385       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1386       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1387       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1388       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1389       if (Subtarget->hasVLX()) {
1390         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1391         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1392         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1393         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1394         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1395         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1396         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1397         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1398       }
1399     }
1400     if (Subtarget->hasVLX()) {
1401       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1402       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1403       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1404       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1405       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1406       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1407       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1408       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1409     }
1410     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1411     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1412     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1413     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1414     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1415     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1416     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1417     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1418     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1419     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1420     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1421     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1422     if (Subtarget->hasDQI()) {
1423       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1424       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1425     }
1426     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1427     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1428     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1429     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1430     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1431     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1432     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1433     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1434     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1435     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1436
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1442
1443     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1444     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1445
1446     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1447
1448     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1449     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1450     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1451     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1452     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1453     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1454     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1455     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1459
1460     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1461     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1462     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1463     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1464     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1465     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1466     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1467     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1468
1469     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1470     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1471
1472     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1473     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1474
1475     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1476
1477     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1478     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1479
1480     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1481     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1482
1483     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1484     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1485
1486     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1487     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1488     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1489     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1490     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1491     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1492
1493     if (Subtarget->hasCDI()) {
1494       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1495       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1496     }
1497     if (Subtarget->hasDQI()) {
1498       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1499       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1500       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1501     }
1502     // Custom lower several nodes.
1503     for (MVT VT : MVT::vector_valuetypes()) {
1504       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1505       if (EltSize == 1) {
1506         setOperationAction(ISD::AND, VT, Legal);
1507         setOperationAction(ISD::OR,  VT, Legal);
1508         setOperationAction(ISD::XOR,  VT, Legal);
1509       }
1510       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1511         setOperationAction(ISD::MGATHER,  VT, Custom);
1512         setOperationAction(ISD::MSCATTER, VT, Custom);
1513       }
1514       // Extract subvector is special because the value type
1515       // (result) is 256/128-bit but the source is 512-bit wide.
1516       if (VT.is128BitVector() || VT.is256BitVector()) {
1517         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1518       }
1519       if (VT.getVectorElementType() == MVT::i1)
1520         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1521
1522       // Do not attempt to custom lower other non-512-bit vectors
1523       if (!VT.is512BitVector())
1524         continue;
1525
1526       if (EltSize >= 32) {
1527         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1528         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1529         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1530         setOperationAction(ISD::VSELECT,             VT, Legal);
1531         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1532         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1533         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1534         setOperationAction(ISD::MLOAD,               VT, Legal);
1535         setOperationAction(ISD::MSTORE,              VT, Legal);
1536       }
1537     }
1538     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1539       MVT VT = (MVT::SimpleValueType)i;
1540
1541       // Do not attempt to promote non-512-bit vectors.
1542       if (!VT.is512BitVector())
1543         continue;
1544
1545       setOperationAction(ISD::SELECT, VT, Promote);
1546       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1547     }
1548   }// has  AVX-512
1549
1550   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1551     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1552     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1553
1554     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1555     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1556
1557     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1558     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1559     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1560     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1561     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1562     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1563     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1564     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1565     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1566     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1567     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1568     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1569     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1570     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1571     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1572     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1573     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1574     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1575     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1576     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1577     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1578     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1579     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1580     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1581     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1582     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1583     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1584     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1585     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1586     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1587
1588     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1589     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1590     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1591     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1592     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1593     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1594     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1595     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1596
1597     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1598     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1599     if (Subtarget->hasVLX())
1600       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1601
1602     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1603       const MVT VT = (MVT::SimpleValueType)i;
1604
1605       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1606
1607       // Do not attempt to promote non-512-bit vectors.
1608       if (!VT.is512BitVector())
1609         continue;
1610
1611       if (EltSize < 32) {
1612         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1613         setOperationAction(ISD::VSELECT,             VT, Legal);
1614       }
1615     }
1616   }
1617
1618   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1619     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1620     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1621
1622     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1623     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1624     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1625     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1626     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1627     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1628     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1629     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1630     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1631     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1632
1633     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1634     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1635     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1636     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1637     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1638     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1639     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1640     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1641
1642     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1643     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1644     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1645     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1646     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1647     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1648     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1649     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1650   }
1651
1652   // We want to custom lower some of our intrinsics.
1653   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1654   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1655   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1656   if (!Subtarget->is64Bit())
1657     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1658
1659   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1660   // handle type legalization for these operations here.
1661   //
1662   // FIXME: We really should do custom legalization for addition and
1663   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1664   // than generic legalization for 64-bit multiplication-with-overflow, though.
1665   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1666     // Add/Sub/Mul with overflow operations are custom lowered.
1667     MVT VT = IntVTs[i];
1668     setOperationAction(ISD::SADDO, VT, Custom);
1669     setOperationAction(ISD::UADDO, VT, Custom);
1670     setOperationAction(ISD::SSUBO, VT, Custom);
1671     setOperationAction(ISD::USUBO, VT, Custom);
1672     setOperationAction(ISD::SMULO, VT, Custom);
1673     setOperationAction(ISD::UMULO, VT, Custom);
1674   }
1675
1676
1677   if (!Subtarget->is64Bit()) {
1678     // These libcalls are not available in 32-bit.
1679     setLibcallName(RTLIB::SHL_I128, nullptr);
1680     setLibcallName(RTLIB::SRL_I128, nullptr);
1681     setLibcallName(RTLIB::SRA_I128, nullptr);
1682   }
1683
1684   // Combine sin / cos into one node or libcall if possible.
1685   if (Subtarget->hasSinCos()) {
1686     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1687     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1688     if (Subtarget->isTargetDarwin()) {
1689       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1690       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1691       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1692       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1693     }
1694   }
1695
1696   if (Subtarget->isTargetWin64()) {
1697     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1698     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1699     setOperationAction(ISD::SREM, MVT::i128, Custom);
1700     setOperationAction(ISD::UREM, MVT::i128, Custom);
1701     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1702     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1703   }
1704
1705   // We have target-specific dag combine patterns for the following nodes:
1706   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1707   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1708   setTargetDAGCombine(ISD::BITCAST);
1709   setTargetDAGCombine(ISD::VSELECT);
1710   setTargetDAGCombine(ISD::SELECT);
1711   setTargetDAGCombine(ISD::SHL);
1712   setTargetDAGCombine(ISD::SRA);
1713   setTargetDAGCombine(ISD::SRL);
1714   setTargetDAGCombine(ISD::OR);
1715   setTargetDAGCombine(ISD::AND);
1716   setTargetDAGCombine(ISD::ADD);
1717   setTargetDAGCombine(ISD::FADD);
1718   setTargetDAGCombine(ISD::FSUB);
1719   setTargetDAGCombine(ISD::FMA);
1720   setTargetDAGCombine(ISD::SUB);
1721   setTargetDAGCombine(ISD::LOAD);
1722   setTargetDAGCombine(ISD::MLOAD);
1723   setTargetDAGCombine(ISD::STORE);
1724   setTargetDAGCombine(ISD::MSTORE);
1725   setTargetDAGCombine(ISD::ZERO_EXTEND);
1726   setTargetDAGCombine(ISD::ANY_EXTEND);
1727   setTargetDAGCombine(ISD::SIGN_EXTEND);
1728   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1729   setTargetDAGCombine(ISD::SINT_TO_FP);
1730   setTargetDAGCombine(ISD::UINT_TO_FP);
1731   setTargetDAGCombine(ISD::SETCC);
1732   setTargetDAGCombine(ISD::BUILD_VECTOR);
1733   setTargetDAGCombine(ISD::MUL);
1734   setTargetDAGCombine(ISD::XOR);
1735
1736   computeRegisterProperties(Subtarget->getRegisterInfo());
1737
1738   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1739   MaxStoresPerMemsetOptSize = 8;
1740   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1741   MaxStoresPerMemcpyOptSize = 4;
1742   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1743   MaxStoresPerMemmoveOptSize = 4;
1744   setPrefLoopAlignment(4); // 2^4 bytes.
1745
1746   // Predictable cmov don't hurt on atom because it's in-order.
1747   PredictableSelectIsExpensive = !Subtarget->isAtom();
1748   EnableExtLdPromotion = true;
1749   setPrefFunctionAlignment(4); // 2^4 bytes.
1750
1751   verifyIntrinsicTables();
1752 }
1753
1754 // This has so far only been implemented for 64-bit MachO.
1755 bool X86TargetLowering::useLoadStackGuardNode() const {
1756   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1757 }
1758
1759 TargetLoweringBase::LegalizeTypeAction
1760 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1761   if (ExperimentalVectorWideningLegalization &&
1762       VT.getVectorNumElements() != 1 &&
1763       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1764     return TypeWidenVector;
1765
1766   return TargetLoweringBase::getPreferredVectorAction(VT);
1767 }
1768
1769 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1770                                           EVT VT) const {
1771   if (!VT.isVector())
1772     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1773
1774   const unsigned NumElts = VT.getVectorNumElements();
1775   const EVT EltVT = VT.getVectorElementType();
1776   if (VT.is512BitVector()) {
1777     if (Subtarget->hasAVX512())
1778       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1779           EltVT == MVT::f32 || EltVT == MVT::f64)
1780         switch(NumElts) {
1781         case  8: return MVT::v8i1;
1782         case 16: return MVT::v16i1;
1783       }
1784     if (Subtarget->hasBWI())
1785       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1786         switch(NumElts) {
1787         case 32: return MVT::v32i1;
1788         case 64: return MVT::v64i1;
1789       }
1790   }
1791
1792   if (VT.is256BitVector() || VT.is128BitVector()) {
1793     if (Subtarget->hasVLX())
1794       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1795           EltVT == MVT::f32 || EltVT == MVT::f64)
1796         switch(NumElts) {
1797         case 2: return MVT::v2i1;
1798         case 4: return MVT::v4i1;
1799         case 8: return MVT::v8i1;
1800       }
1801     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1802       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1803         switch(NumElts) {
1804         case  8: return MVT::v8i1;
1805         case 16: return MVT::v16i1;
1806         case 32: return MVT::v32i1;
1807       }
1808   }
1809
1810   return VT.changeVectorElementTypeToInteger();
1811 }
1812
1813 /// Helper for getByValTypeAlignment to determine
1814 /// the desired ByVal argument alignment.
1815 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1816   if (MaxAlign == 16)
1817     return;
1818   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1819     if (VTy->getBitWidth() == 128)
1820       MaxAlign = 16;
1821   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1822     unsigned EltAlign = 0;
1823     getMaxByValAlign(ATy->getElementType(), EltAlign);
1824     if (EltAlign > MaxAlign)
1825       MaxAlign = EltAlign;
1826   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1827     for (auto *EltTy : STy->elements()) {
1828       unsigned EltAlign = 0;
1829       getMaxByValAlign(EltTy, EltAlign);
1830       if (EltAlign > MaxAlign)
1831         MaxAlign = EltAlign;
1832       if (MaxAlign == 16)
1833         break;
1834     }
1835   }
1836 }
1837
1838 /// Return the desired alignment for ByVal aggregate
1839 /// function arguments in the caller parameter area. For X86, aggregates
1840 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1841 /// are at 4-byte boundaries.
1842 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1843                                                   const DataLayout &DL) const {
1844   if (Subtarget->is64Bit()) {
1845     // Max of 8 and alignment of type.
1846     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1847     if (TyAlign > 8)
1848       return TyAlign;
1849     return 8;
1850   }
1851
1852   unsigned Align = 4;
1853   if (Subtarget->hasSSE1())
1854     getMaxByValAlign(Ty, Align);
1855   return Align;
1856 }
1857
1858 /// Returns the target specific optimal type for load
1859 /// and store operations as a result of memset, memcpy, and memmove
1860 /// lowering. If DstAlign is zero that means it's safe to destination
1861 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1862 /// means there isn't a need to check it against alignment requirement,
1863 /// probably because the source does not need to be loaded. If 'IsMemset' is
1864 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1865 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1866 /// source is constant so it does not need to be loaded.
1867 /// It returns EVT::Other if the type should be determined using generic
1868 /// target-independent logic.
1869 EVT
1870 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1871                                        unsigned DstAlign, unsigned SrcAlign,
1872                                        bool IsMemset, bool ZeroMemset,
1873                                        bool MemcpyStrSrc,
1874                                        MachineFunction &MF) const {
1875   const Function *F = MF.getFunction();
1876   if ((!IsMemset || ZeroMemset) &&
1877       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1878     if (Size >= 16 &&
1879         (Subtarget->isUnalignedMemAccessFast() ||
1880          ((DstAlign == 0 || DstAlign >= 16) &&
1881           (SrcAlign == 0 || SrcAlign >= 16)))) {
1882       if (Size >= 32) {
1883         if (Subtarget->hasInt256())
1884           return MVT::v8i32;
1885         if (Subtarget->hasFp256())
1886           return MVT::v8f32;
1887       }
1888       if (Subtarget->hasSSE2())
1889         return MVT::v4i32;
1890       if (Subtarget->hasSSE1())
1891         return MVT::v4f32;
1892     } else if (!MemcpyStrSrc && Size >= 8 &&
1893                !Subtarget->is64Bit() &&
1894                Subtarget->hasSSE2()) {
1895       // Do not use f64 to lower memcpy if source is string constant. It's
1896       // better to use i32 to avoid the loads.
1897       return MVT::f64;
1898     }
1899   }
1900   if (Subtarget->is64Bit() && Size >= 8)
1901     return MVT::i64;
1902   return MVT::i32;
1903 }
1904
1905 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1906   if (VT == MVT::f32)
1907     return X86ScalarSSEf32;
1908   else if (VT == MVT::f64)
1909     return X86ScalarSSEf64;
1910   return true;
1911 }
1912
1913 bool
1914 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1915                                                   unsigned,
1916                                                   unsigned,
1917                                                   bool *Fast) const {
1918   if (Fast)
1919     *Fast = Subtarget->isUnalignedMemAccessFast();
1920   return true;
1921 }
1922
1923 /// Return the entry encoding for a jump table in the
1924 /// current function.  The returned value is a member of the
1925 /// MachineJumpTableInfo::JTEntryKind enum.
1926 unsigned X86TargetLowering::getJumpTableEncoding() const {
1927   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1928   // symbol.
1929   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1930       Subtarget->isPICStyleGOT())
1931     return MachineJumpTableInfo::EK_Custom32;
1932
1933   // Otherwise, use the normal jump table encoding heuristics.
1934   return TargetLowering::getJumpTableEncoding();
1935 }
1936
1937 bool X86TargetLowering::useSoftFloat() const {
1938   return Subtarget->useSoftFloat();
1939 }
1940
1941 const MCExpr *
1942 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1943                                              const MachineBasicBlock *MBB,
1944                                              unsigned uid,MCContext &Ctx) const{
1945   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1946          Subtarget->isPICStyleGOT());
1947   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1948   // entries.
1949   return MCSymbolRefExpr::create(MBB->getSymbol(),
1950                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1951 }
1952
1953 /// Returns relocation base for the given PIC jumptable.
1954 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1955                                                     SelectionDAG &DAG) const {
1956   if (!Subtarget->is64Bit())
1957     // This doesn't have SDLoc associated with it, but is not really the
1958     // same as a Register.
1959     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1960                        getPointerTy(DAG.getDataLayout()));
1961   return Table;
1962 }
1963
1964 /// This returns the relocation base for the given PIC jumptable,
1965 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1966 const MCExpr *X86TargetLowering::
1967 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1968                              MCContext &Ctx) const {
1969   // X86-64 uses RIP relative addressing based on the jump table label.
1970   if (Subtarget->isPICStyleRIPRel())
1971     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1972
1973   // Otherwise, the reference is relative to the PIC base.
1974   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1975 }
1976
1977 std::pair<const TargetRegisterClass *, uint8_t>
1978 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1979                                            MVT VT) const {
1980   const TargetRegisterClass *RRC = nullptr;
1981   uint8_t Cost = 1;
1982   switch (VT.SimpleTy) {
1983   default:
1984     return TargetLowering::findRepresentativeClass(TRI, VT);
1985   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1986     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1987     break;
1988   case MVT::x86mmx:
1989     RRC = &X86::VR64RegClass;
1990     break;
1991   case MVT::f32: case MVT::f64:
1992   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1993   case MVT::v4f32: case MVT::v2f64:
1994   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1995   case MVT::v4f64:
1996     RRC = &X86::VR128RegClass;
1997     break;
1998   }
1999   return std::make_pair(RRC, Cost);
2000 }
2001
2002 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2003                                                unsigned &Offset) const {
2004   if (!Subtarget->isTargetLinux())
2005     return false;
2006
2007   if (Subtarget->is64Bit()) {
2008     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2009     Offset = 0x28;
2010     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2011       AddressSpace = 256;
2012     else
2013       AddressSpace = 257;
2014   } else {
2015     // %gs:0x14 on i386
2016     Offset = 0x14;
2017     AddressSpace = 256;
2018   }
2019   return true;
2020 }
2021
2022 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2023                                             unsigned DestAS) const {
2024   assert(SrcAS != DestAS && "Expected different address spaces!");
2025
2026   return SrcAS < 256 && DestAS < 256;
2027 }
2028
2029 //===----------------------------------------------------------------------===//
2030 //               Return Value Calling Convention Implementation
2031 //===----------------------------------------------------------------------===//
2032
2033 #include "X86GenCallingConv.inc"
2034
2035 bool
2036 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2037                                   MachineFunction &MF, bool isVarArg,
2038                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2039                         LLVMContext &Context) const {
2040   SmallVector<CCValAssign, 16> RVLocs;
2041   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2042   return CCInfo.CheckReturn(Outs, RetCC_X86);
2043 }
2044
2045 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2046   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2047   return ScratchRegs;
2048 }
2049
2050 SDValue
2051 X86TargetLowering::LowerReturn(SDValue Chain,
2052                                CallingConv::ID CallConv, bool isVarArg,
2053                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2054                                const SmallVectorImpl<SDValue> &OutVals,
2055                                SDLoc dl, SelectionDAG &DAG) const {
2056   MachineFunction &MF = DAG.getMachineFunction();
2057   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2058
2059   SmallVector<CCValAssign, 16> RVLocs;
2060   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2061   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2062
2063   SDValue Flag;
2064   SmallVector<SDValue, 6> RetOps;
2065   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2066   // Operand #1 = Bytes To Pop
2067   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2068                    MVT::i16));
2069
2070   // Copy the result values into the output registers.
2071   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2072     CCValAssign &VA = RVLocs[i];
2073     assert(VA.isRegLoc() && "Can only return in registers!");
2074     SDValue ValToCopy = OutVals[i];
2075     EVT ValVT = ValToCopy.getValueType();
2076
2077     // Promote values to the appropriate types.
2078     if (VA.getLocInfo() == CCValAssign::SExt)
2079       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2080     else if (VA.getLocInfo() == CCValAssign::ZExt)
2081       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2082     else if (VA.getLocInfo() == CCValAssign::AExt) {
2083       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2084         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2085       else
2086         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2087     }
2088     else if (VA.getLocInfo() == CCValAssign::BCvt)
2089       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2090
2091     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2092            "Unexpected FP-extend for return value.");
2093
2094     // If this is x86-64, and we disabled SSE, we can't return FP values,
2095     // or SSE or MMX vectors.
2096     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2097          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2098           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2099       report_fatal_error("SSE register return with SSE disabled");
2100     }
2101     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2102     // llvm-gcc has never done it right and no one has noticed, so this
2103     // should be OK for now.
2104     if (ValVT == MVT::f64 &&
2105         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2106       report_fatal_error("SSE2 register return with SSE2 disabled");
2107
2108     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2109     // the RET instruction and handled by the FP Stackifier.
2110     if (VA.getLocReg() == X86::FP0 ||
2111         VA.getLocReg() == X86::FP1) {
2112       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2113       // change the value to the FP stack register class.
2114       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2115         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2116       RetOps.push_back(ValToCopy);
2117       // Don't emit a copytoreg.
2118       continue;
2119     }
2120
2121     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2122     // which is returned in RAX / RDX.
2123     if (Subtarget->is64Bit()) {
2124       if (ValVT == MVT::x86mmx) {
2125         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2126           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2127           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2128                                   ValToCopy);
2129           // If we don't have SSE2 available, convert to v4f32 so the generated
2130           // register is legal.
2131           if (!Subtarget->hasSSE2())
2132             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2133         }
2134       }
2135     }
2136
2137     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2138     Flag = Chain.getValue(1);
2139     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2140   }
2141
2142   // All x86 ABIs require that for returning structs by value we copy
2143   // the sret argument into %rax/%eax (depending on ABI) for the return.
2144   // We saved the argument into a virtual register in the entry block,
2145   // so now we copy the value out and into %rax/%eax.
2146   //
2147   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2148   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2149   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2150   // either case FuncInfo->setSRetReturnReg() will have been called.
2151   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2152     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2153                                      getPointerTy(MF.getDataLayout()));
2154
2155     unsigned RetValReg
2156         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2157           X86::RAX : X86::EAX;
2158     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2159     Flag = Chain.getValue(1);
2160
2161     // RAX/EAX now acts like a return value.
2162     RetOps.push_back(
2163         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2164   }
2165
2166   RetOps[0] = Chain;  // Update chain.
2167
2168   // Add the flag if we have it.
2169   if (Flag.getNode())
2170     RetOps.push_back(Flag);
2171
2172   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2173 }
2174
2175 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2176   if (N->getNumValues() != 1)
2177     return false;
2178   if (!N->hasNUsesOfValue(1, 0))
2179     return false;
2180
2181   SDValue TCChain = Chain;
2182   SDNode *Copy = *N->use_begin();
2183   if (Copy->getOpcode() == ISD::CopyToReg) {
2184     // If the copy has a glue operand, we conservatively assume it isn't safe to
2185     // perform a tail call.
2186     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2187       return false;
2188     TCChain = Copy->getOperand(0);
2189   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2190     return false;
2191
2192   bool HasRet = false;
2193   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2194        UI != UE; ++UI) {
2195     if (UI->getOpcode() != X86ISD::RET_FLAG)
2196       return false;
2197     // If we are returning more than one value, we can definitely
2198     // not make a tail call see PR19530
2199     if (UI->getNumOperands() > 4)
2200       return false;
2201     if (UI->getNumOperands() == 4 &&
2202         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2203       return false;
2204     HasRet = true;
2205   }
2206
2207   if (!HasRet)
2208     return false;
2209
2210   Chain = TCChain;
2211   return true;
2212 }
2213
2214 EVT
2215 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2216                                             ISD::NodeType ExtendKind) const {
2217   MVT ReturnMVT;
2218   // TODO: Is this also valid on 32-bit?
2219   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2220     ReturnMVT = MVT::i8;
2221   else
2222     ReturnMVT = MVT::i32;
2223
2224   EVT MinVT = getRegisterType(Context, ReturnMVT);
2225   return VT.bitsLT(MinVT) ? MinVT : VT;
2226 }
2227
2228 /// Lower the result values of a call into the
2229 /// appropriate copies out of appropriate physical registers.
2230 ///
2231 SDValue
2232 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2233                                    CallingConv::ID CallConv, bool isVarArg,
2234                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2235                                    SDLoc dl, SelectionDAG &DAG,
2236                                    SmallVectorImpl<SDValue> &InVals) const {
2237
2238   // Assign locations to each value returned by this call.
2239   SmallVector<CCValAssign, 16> RVLocs;
2240   bool Is64Bit = Subtarget->is64Bit();
2241   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2242                  *DAG.getContext());
2243   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2244
2245   // Copy all of the result registers out of their specified physreg.
2246   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2247     CCValAssign &VA = RVLocs[i];
2248     EVT CopyVT = VA.getLocVT();
2249
2250     // If this is x86-64, and we disabled SSE, we can't return FP values
2251     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2252         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2253       report_fatal_error("SSE register return with SSE disabled");
2254     }
2255
2256     // If we prefer to use the value in xmm registers, copy it out as f80 and
2257     // use a truncate to move it from fp stack reg to xmm reg.
2258     bool RoundAfterCopy = false;
2259     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2260         isScalarFPTypeInSSEReg(VA.getValVT())) {
2261       CopyVT = MVT::f80;
2262       RoundAfterCopy = (CopyVT != VA.getLocVT());
2263     }
2264
2265     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2266                                CopyVT, InFlag).getValue(1);
2267     SDValue Val = Chain.getValue(0);
2268
2269     if (RoundAfterCopy)
2270       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2271                         // This truncation won't change the value.
2272                         DAG.getIntPtrConstant(1, dl));
2273
2274     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2275       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2276
2277     InFlag = Chain.getValue(2);
2278     InVals.push_back(Val);
2279   }
2280
2281   return Chain;
2282 }
2283
2284 //===----------------------------------------------------------------------===//
2285 //                C & StdCall & Fast Calling Convention implementation
2286 //===----------------------------------------------------------------------===//
2287 //  StdCall calling convention seems to be standard for many Windows' API
2288 //  routines and around. It differs from C calling convention just a little:
2289 //  callee should clean up the stack, not caller. Symbols should be also
2290 //  decorated in some fancy way :) It doesn't support any vector arguments.
2291 //  For info on fast calling convention see Fast Calling Convention (tail call)
2292 //  implementation LowerX86_32FastCCCallTo.
2293
2294 /// CallIsStructReturn - Determines whether a call uses struct return
2295 /// semantics.
2296 enum StructReturnType {
2297   NotStructReturn,
2298   RegStructReturn,
2299   StackStructReturn
2300 };
2301 static StructReturnType
2302 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2303   if (Outs.empty())
2304     return NotStructReturn;
2305
2306   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2307   if (!Flags.isSRet())
2308     return NotStructReturn;
2309   if (Flags.isInReg())
2310     return RegStructReturn;
2311   return StackStructReturn;
2312 }
2313
2314 /// Determines whether a function uses struct return semantics.
2315 static StructReturnType
2316 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2317   if (Ins.empty())
2318     return NotStructReturn;
2319
2320   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2321   if (!Flags.isSRet())
2322     return NotStructReturn;
2323   if (Flags.isInReg())
2324     return RegStructReturn;
2325   return StackStructReturn;
2326 }
2327
2328 /// Make a copy of an aggregate at address specified by "Src" to address
2329 /// "Dst" with size and alignment information specified by the specific
2330 /// parameter attribute. The copy will be passed as a byval function parameter.
2331 static SDValue
2332 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2333                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2334                           SDLoc dl) {
2335   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2336
2337   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2338                        /*isVolatile*/false, /*AlwaysInline=*/true,
2339                        /*isTailCall*/false,
2340                        MachinePointerInfo(), MachinePointerInfo());
2341 }
2342
2343 /// Return true if the calling convention is one that
2344 /// supports tail call optimization.
2345 static bool IsTailCallConvention(CallingConv::ID CC) {
2346   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2347           CC == CallingConv::HiPE);
2348 }
2349
2350 /// \brief Return true if the calling convention is a C calling convention.
2351 static bool IsCCallConvention(CallingConv::ID CC) {
2352   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2353           CC == CallingConv::X86_64_SysV);
2354 }
2355
2356 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2357   auto Attr =
2358       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2359   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2360     return false;
2361
2362   CallSite CS(CI);
2363   CallingConv::ID CalleeCC = CS.getCallingConv();
2364   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2365     return false;
2366
2367   return true;
2368 }
2369
2370 /// Return true if the function is being made into
2371 /// a tailcall target by changing its ABI.
2372 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2373                                    bool GuaranteedTailCallOpt) {
2374   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2375 }
2376
2377 SDValue
2378 X86TargetLowering::LowerMemArgument(SDValue Chain,
2379                                     CallingConv::ID CallConv,
2380                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2381                                     SDLoc dl, SelectionDAG &DAG,
2382                                     const CCValAssign &VA,
2383                                     MachineFrameInfo *MFI,
2384                                     unsigned i) const {
2385   // Create the nodes corresponding to a load from this parameter slot.
2386   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2387   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2388       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2389   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2390   EVT ValVT;
2391
2392   // If value is passed by pointer we have address passed instead of the value
2393   // itself.
2394   bool ExtendedInMem = VA.isExtInLoc() &&
2395     VA.getValVT().getScalarType() == MVT::i1;
2396
2397   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2398     ValVT = VA.getLocVT();
2399   else
2400     ValVT = VA.getValVT();
2401
2402   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2403   // changed with more analysis.
2404   // In case of tail call optimization mark all arguments mutable. Since they
2405   // could be overwritten by lowering of arguments in case of a tail call.
2406   if (Flags.isByVal()) {
2407     unsigned Bytes = Flags.getByValSize();
2408     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2409     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2410     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2411   } else {
2412     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2413                                     VA.getLocMemOffset(), isImmutable);
2414     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2415     SDValue Val = DAG.getLoad(
2416         ValVT, dl, Chain, FIN,
2417         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2418         false, false, 0);
2419     return ExtendedInMem ?
2420       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2421   }
2422 }
2423
2424 // FIXME: Get this from tablegen.
2425 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2426                                                 const X86Subtarget *Subtarget) {
2427   assert(Subtarget->is64Bit());
2428
2429   if (Subtarget->isCallingConvWin64(CallConv)) {
2430     static const MCPhysReg GPR64ArgRegsWin64[] = {
2431       X86::RCX, X86::RDX, X86::R8,  X86::R9
2432     };
2433     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2434   }
2435
2436   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2437     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2438   };
2439   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2440 }
2441
2442 // FIXME: Get this from tablegen.
2443 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2444                                                 CallingConv::ID CallConv,
2445                                                 const X86Subtarget *Subtarget) {
2446   assert(Subtarget->is64Bit());
2447   if (Subtarget->isCallingConvWin64(CallConv)) {
2448     // The XMM registers which might contain var arg parameters are shadowed
2449     // in their paired GPR.  So we only need to save the GPR to their home
2450     // slots.
2451     // TODO: __vectorcall will change this.
2452     return None;
2453   }
2454
2455   const Function *Fn = MF.getFunction();
2456   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2457   bool isSoftFloat = Subtarget->useSoftFloat();
2458   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2459          "SSE register cannot be used when SSE is disabled!");
2460   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2461     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2462     // registers.
2463     return None;
2464
2465   static const MCPhysReg XMMArgRegs64Bit[] = {
2466     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2467     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2468   };
2469   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2470 }
2471
2472 SDValue
2473 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2474                                         CallingConv::ID CallConv,
2475                                         bool isVarArg,
2476                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2477                                         SDLoc dl,
2478                                         SelectionDAG &DAG,
2479                                         SmallVectorImpl<SDValue> &InVals)
2480                                           const {
2481   MachineFunction &MF = DAG.getMachineFunction();
2482   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2483   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2484
2485   const Function* Fn = MF.getFunction();
2486   if (Fn->hasExternalLinkage() &&
2487       Subtarget->isTargetCygMing() &&
2488       Fn->getName() == "main")
2489     FuncInfo->setForceFramePointer(true);
2490
2491   MachineFrameInfo *MFI = MF.getFrameInfo();
2492   bool Is64Bit = Subtarget->is64Bit();
2493   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2494
2495   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2496          "Var args not supported with calling convention fastcc, ghc or hipe");
2497
2498   // Assign locations to all of the incoming arguments.
2499   SmallVector<CCValAssign, 16> ArgLocs;
2500   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2501
2502   // Allocate shadow area for Win64
2503   if (IsWin64)
2504     CCInfo.AllocateStack(32, 8);
2505
2506   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2507
2508   unsigned LastVal = ~0U;
2509   SDValue ArgValue;
2510   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2511     CCValAssign &VA = ArgLocs[i];
2512     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2513     // places.
2514     assert(VA.getValNo() != LastVal &&
2515            "Don't support value assigned to multiple locs yet");
2516     (void)LastVal;
2517     LastVal = VA.getValNo();
2518
2519     if (VA.isRegLoc()) {
2520       EVT RegVT = VA.getLocVT();
2521       const TargetRegisterClass *RC;
2522       if (RegVT == MVT::i32)
2523         RC = &X86::GR32RegClass;
2524       else if (Is64Bit && RegVT == MVT::i64)
2525         RC = &X86::GR64RegClass;
2526       else if (RegVT == MVT::f32)
2527         RC = &X86::FR32RegClass;
2528       else if (RegVT == MVT::f64)
2529         RC = &X86::FR64RegClass;
2530       else if (RegVT.is512BitVector())
2531         RC = &X86::VR512RegClass;
2532       else if (RegVT.is256BitVector())
2533         RC = &X86::VR256RegClass;
2534       else if (RegVT.is128BitVector())
2535         RC = &X86::VR128RegClass;
2536       else if (RegVT == MVT::x86mmx)
2537         RC = &X86::VR64RegClass;
2538       else if (RegVT == MVT::i1)
2539         RC = &X86::VK1RegClass;
2540       else if (RegVT == MVT::v8i1)
2541         RC = &X86::VK8RegClass;
2542       else if (RegVT == MVT::v16i1)
2543         RC = &X86::VK16RegClass;
2544       else if (RegVT == MVT::v32i1)
2545         RC = &X86::VK32RegClass;
2546       else if (RegVT == MVT::v64i1)
2547         RC = &X86::VK64RegClass;
2548       else
2549         llvm_unreachable("Unknown argument type!");
2550
2551       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2552       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2553
2554       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2555       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2556       // right size.
2557       if (VA.getLocInfo() == CCValAssign::SExt)
2558         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2559                                DAG.getValueType(VA.getValVT()));
2560       else if (VA.getLocInfo() == CCValAssign::ZExt)
2561         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2562                                DAG.getValueType(VA.getValVT()));
2563       else if (VA.getLocInfo() == CCValAssign::BCvt)
2564         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2565
2566       if (VA.isExtInLoc()) {
2567         // Handle MMX values passed in XMM regs.
2568         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2569           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2570         else
2571           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2572       }
2573     } else {
2574       assert(VA.isMemLoc());
2575       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2576     }
2577
2578     // If value is passed via pointer - do a load.
2579     if (VA.getLocInfo() == CCValAssign::Indirect)
2580       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2581                              MachinePointerInfo(), false, false, false, 0);
2582
2583     InVals.push_back(ArgValue);
2584   }
2585
2586   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2587     // All x86 ABIs require that for returning structs by value we copy the
2588     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2589     // the argument into a virtual register so that we can access it from the
2590     // return points.
2591     if (Ins[i].Flags.isSRet()) {
2592       unsigned Reg = FuncInfo->getSRetReturnReg();
2593       if (!Reg) {
2594         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2595         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2596         FuncInfo->setSRetReturnReg(Reg);
2597       }
2598       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2599       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2600       break;
2601     }
2602   }
2603
2604   unsigned StackSize = CCInfo.getNextStackOffset();
2605   // Align stack specially for tail calls.
2606   if (FuncIsMadeTailCallSafe(CallConv,
2607                              MF.getTarget().Options.GuaranteedTailCallOpt))
2608     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2609
2610   // If the function takes variable number of arguments, make a frame index for
2611   // the start of the first vararg value... for expansion of llvm.va_start. We
2612   // can skip this if there are no va_start calls.
2613   if (MFI->hasVAStart() &&
2614       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2615                    CallConv != CallingConv::X86_ThisCall))) {
2616     FuncInfo->setVarArgsFrameIndex(
2617         MFI->CreateFixedObject(1, StackSize, true));
2618   }
2619
2620   MachineModuleInfo &MMI = MF.getMMI();
2621   const Function *WinEHParent = nullptr;
2622   if (MMI.hasWinEHFuncInfo(Fn))
2623     WinEHParent = MMI.getWinEHParent(Fn);
2624   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2625   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2626
2627   // Figure out if XMM registers are in use.
2628   assert(!(Subtarget->useSoftFloat() &&
2629            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2630          "SSE register cannot be used when SSE is disabled!");
2631
2632   // 64-bit calling conventions support varargs and register parameters, so we
2633   // have to do extra work to spill them in the prologue.
2634   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2635     // Find the first unallocated argument registers.
2636     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2637     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2638     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2639     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2640     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2641            "SSE register cannot be used when SSE is disabled!");
2642
2643     // Gather all the live in physical registers.
2644     SmallVector<SDValue, 6> LiveGPRs;
2645     SmallVector<SDValue, 8> LiveXMMRegs;
2646     SDValue ALVal;
2647     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2648       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2649       LiveGPRs.push_back(
2650           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2651     }
2652     if (!ArgXMMs.empty()) {
2653       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2654       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2655       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2656         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2657         LiveXMMRegs.push_back(
2658             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2659       }
2660     }
2661
2662     if (IsWin64) {
2663       // Get to the caller-allocated home save location.  Add 8 to account
2664       // for the return address.
2665       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2666       FuncInfo->setRegSaveFrameIndex(
2667           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2668       // Fixup to set vararg frame on shadow area (4 x i64).
2669       if (NumIntRegs < 4)
2670         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2671     } else {
2672       // For X86-64, if there are vararg parameters that are passed via
2673       // registers, then we must store them to their spots on the stack so
2674       // they may be loaded by deferencing the result of va_next.
2675       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2676       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2677       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2678           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2679     }
2680
2681     // Store the integer parameter registers.
2682     SmallVector<SDValue, 8> MemOps;
2683     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2684                                       getPointerTy(DAG.getDataLayout()));
2685     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2686     for (SDValue Val : LiveGPRs) {
2687       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2688                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2689       SDValue Store =
2690           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2691                        MachinePointerInfo::getFixedStack(
2692                            DAG.getMachineFunction(),
2693                            FuncInfo->getRegSaveFrameIndex(), Offset),
2694                        false, false, 0);
2695       MemOps.push_back(Store);
2696       Offset += 8;
2697     }
2698
2699     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2700       // Now store the XMM (fp + vector) parameter registers.
2701       SmallVector<SDValue, 12> SaveXMMOps;
2702       SaveXMMOps.push_back(Chain);
2703       SaveXMMOps.push_back(ALVal);
2704       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2705                              FuncInfo->getRegSaveFrameIndex(), dl));
2706       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2707                              FuncInfo->getVarArgsFPOffset(), dl));
2708       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2709                         LiveXMMRegs.end());
2710       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2711                                    MVT::Other, SaveXMMOps));
2712     }
2713
2714     if (!MemOps.empty())
2715       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2716   } else if (IsWin64 && IsWinEHOutlined) {
2717     // Get to the caller-allocated home save location.  Add 8 to account
2718     // for the return address.
2719     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2720     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2721         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2722
2723     MMI.getWinEHFuncInfo(Fn)
2724         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2725         FuncInfo->getRegSaveFrameIndex();
2726
2727     // Store the second integer parameter (rdx) into rsp+16 relative to the
2728     // stack pointer at the entry of the function.
2729     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2730                                       getPointerTy(DAG.getDataLayout()));
2731     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2732     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2733     Chain = DAG.getStore(
2734         Val.getValue(1), dl, Val, RSFIN,
2735         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2736                                           FuncInfo->getRegSaveFrameIndex()),
2737         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2738   }
2739
2740   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2741     // Find the largest legal vector type.
2742     MVT VecVT = MVT::Other;
2743     // FIXME: Only some x86_32 calling conventions support AVX512.
2744     if (Subtarget->hasAVX512() &&
2745         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2746                      CallConv == CallingConv::Intel_OCL_BI)))
2747       VecVT = MVT::v16f32;
2748     else if (Subtarget->hasAVX())
2749       VecVT = MVT::v8f32;
2750     else if (Subtarget->hasSSE2())
2751       VecVT = MVT::v4f32;
2752
2753     // We forward some GPRs and some vector types.
2754     SmallVector<MVT, 2> RegParmTypes;
2755     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2756     RegParmTypes.push_back(IntVT);
2757     if (VecVT != MVT::Other)
2758       RegParmTypes.push_back(VecVT);
2759
2760     // Compute the set of forwarded registers. The rest are scratch.
2761     SmallVectorImpl<ForwardedRegister> &Forwards =
2762         FuncInfo->getForwardedMustTailRegParms();
2763     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2764
2765     // Conservatively forward AL on x86_64, since it might be used for varargs.
2766     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2767       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2768       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2769     }
2770
2771     // Copy all forwards from physical to virtual registers.
2772     for (ForwardedRegister &F : Forwards) {
2773       // FIXME: Can we use a less constrained schedule?
2774       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2775       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2776       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2777     }
2778   }
2779
2780   // Some CCs need callee pop.
2781   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2782                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2783     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2784   } else {
2785     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2786     // If this is an sret function, the return should pop the hidden pointer.
2787     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2788         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2789         argsAreStructReturn(Ins) == StackStructReturn)
2790       FuncInfo->setBytesToPopOnReturn(4);
2791   }
2792
2793   if (!Is64Bit) {
2794     // RegSaveFrameIndex is X86-64 only.
2795     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2796     if (CallConv == CallingConv::X86_FastCall ||
2797         CallConv == CallingConv::X86_ThisCall)
2798       // fastcc functions can't have varargs.
2799       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2800   }
2801
2802   FuncInfo->setArgumentStackSize(StackSize);
2803
2804   if (IsWinEHParent) {
2805     if (Is64Bit) {
2806       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2807       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2808       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2809       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2810       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2811                            MachinePointerInfo::getFixedStack(
2812                                DAG.getMachineFunction(), UnwindHelpFI),
2813                            /*isVolatile=*/true,
2814                            /*isNonTemporal=*/false, /*Alignment=*/0);
2815     } else {
2816       // Functions using Win32 EH are considered to have opaque SP adjustments
2817       // to force local variables to be addressed from the frame or base
2818       // pointers.
2819       MFI->setHasOpaqueSPAdjustment(true);
2820     }
2821   }
2822
2823   return Chain;
2824 }
2825
2826 SDValue
2827 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2828                                     SDValue StackPtr, SDValue Arg,
2829                                     SDLoc dl, SelectionDAG &DAG,
2830                                     const CCValAssign &VA,
2831                                     ISD::ArgFlagsTy Flags) const {
2832   unsigned LocMemOffset = VA.getLocMemOffset();
2833   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2834   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2835                        StackPtr, PtrOff);
2836   if (Flags.isByVal())
2837     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2838
2839   return DAG.getStore(
2840       Chain, dl, Arg, PtrOff,
2841       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2842       false, false, 0);
2843 }
2844
2845 /// Emit a load of return address if tail call
2846 /// optimization is performed and it is required.
2847 SDValue
2848 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2849                                            SDValue &OutRetAddr, SDValue Chain,
2850                                            bool IsTailCall, bool Is64Bit,
2851                                            int FPDiff, SDLoc dl) const {
2852   // Adjust the Return address stack slot.
2853   EVT VT = getPointerTy(DAG.getDataLayout());
2854   OutRetAddr = getReturnAddressFrameIndex(DAG);
2855
2856   // Load the "old" Return address.
2857   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2858                            false, false, false, 0);
2859   return SDValue(OutRetAddr.getNode(), 1);
2860 }
2861
2862 /// Emit a store of the return address if tail call
2863 /// optimization is performed and it is required (FPDiff!=0).
2864 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2865                                         SDValue Chain, SDValue RetAddrFrIdx,
2866                                         EVT PtrVT, unsigned SlotSize,
2867                                         int FPDiff, SDLoc dl) {
2868   // Store the return address to the appropriate stack slot.
2869   if (!FPDiff) return Chain;
2870   // Calculate the new stack slot for the return address.
2871   int NewReturnAddrFI =
2872     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2873                                          false);
2874   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2875   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2876                        MachinePointerInfo::getFixedStack(
2877                            DAG.getMachineFunction(), NewReturnAddrFI),
2878                        false, false, 0);
2879   return Chain;
2880 }
2881
2882 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2883 /// operation of specified width.
2884 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2885                        SDValue V2) {
2886   unsigned NumElems = VT.getVectorNumElements();
2887   SmallVector<int, 8> Mask;
2888   Mask.push_back(NumElems);
2889   for (unsigned i = 1; i != NumElems; ++i)
2890     Mask.push_back(i);
2891   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2892 }
2893
2894 SDValue
2895 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2896                              SmallVectorImpl<SDValue> &InVals) const {
2897   SelectionDAG &DAG                     = CLI.DAG;
2898   SDLoc &dl                             = CLI.DL;
2899   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2900   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2901   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2902   SDValue Chain                         = CLI.Chain;
2903   SDValue Callee                        = CLI.Callee;
2904   CallingConv::ID CallConv              = CLI.CallConv;
2905   bool &isTailCall                      = CLI.IsTailCall;
2906   bool isVarArg                         = CLI.IsVarArg;
2907
2908   MachineFunction &MF = DAG.getMachineFunction();
2909   bool Is64Bit        = Subtarget->is64Bit();
2910   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2911   StructReturnType SR = callIsStructReturn(Outs);
2912   bool IsSibcall      = false;
2913   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2914   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2915
2916   if (Attr.getValueAsString() == "true")
2917     isTailCall = false;
2918
2919   if (Subtarget->isPICStyleGOT() &&
2920       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2921     // If we are using a GOT, disable tail calls to external symbols with
2922     // default visibility. Tail calling such a symbol requires using a GOT
2923     // relocation, which forces early binding of the symbol. This breaks code
2924     // that require lazy function symbol resolution. Using musttail or
2925     // GuaranteedTailCallOpt will override this.
2926     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2927     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2928                G->getGlobal()->hasDefaultVisibility()))
2929       isTailCall = false;
2930   }
2931
2932   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2933   if (IsMustTail) {
2934     // Force this to be a tail call.  The verifier rules are enough to ensure
2935     // that we can lower this successfully without moving the return address
2936     // around.
2937     isTailCall = true;
2938   } else if (isTailCall) {
2939     // Check if it's really possible to do a tail call.
2940     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2941                     isVarArg, SR != NotStructReturn,
2942                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2943                     Outs, OutVals, Ins, DAG);
2944
2945     // Sibcalls are automatically detected tailcalls which do not require
2946     // ABI changes.
2947     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2948       IsSibcall = true;
2949
2950     if (isTailCall)
2951       ++NumTailCalls;
2952   }
2953
2954   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2955          "Var args not supported with calling convention fastcc, ghc or hipe");
2956
2957   // Analyze operands of the call, assigning locations to each operand.
2958   SmallVector<CCValAssign, 16> ArgLocs;
2959   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2960
2961   // Allocate shadow area for Win64
2962   if (IsWin64)
2963     CCInfo.AllocateStack(32, 8);
2964
2965   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2966
2967   // Get a count of how many bytes are to be pushed on the stack.
2968   unsigned NumBytes = CCInfo.getNextStackOffset();
2969   if (IsSibcall)
2970     // This is a sibcall. The memory operands are available in caller's
2971     // own caller's stack.
2972     NumBytes = 0;
2973   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2974            IsTailCallConvention(CallConv))
2975     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2976
2977   int FPDiff = 0;
2978   if (isTailCall && !IsSibcall && !IsMustTail) {
2979     // Lower arguments at fp - stackoffset + fpdiff.
2980     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2981
2982     FPDiff = NumBytesCallerPushed - NumBytes;
2983
2984     // Set the delta of movement of the returnaddr stackslot.
2985     // But only set if delta is greater than previous delta.
2986     if (FPDiff < X86Info->getTCReturnAddrDelta())
2987       X86Info->setTCReturnAddrDelta(FPDiff);
2988   }
2989
2990   unsigned NumBytesToPush = NumBytes;
2991   unsigned NumBytesToPop = NumBytes;
2992
2993   // If we have an inalloca argument, all stack space has already been allocated
2994   // for us and be right at the top of the stack.  We don't support multiple
2995   // arguments passed in memory when using inalloca.
2996   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2997     NumBytesToPush = 0;
2998     if (!ArgLocs.back().isMemLoc())
2999       report_fatal_error("cannot use inalloca attribute on a register "
3000                          "parameter");
3001     if (ArgLocs.back().getLocMemOffset() != 0)
3002       report_fatal_error("any parameter with the inalloca attribute must be "
3003                          "the only memory argument");
3004   }
3005
3006   if (!IsSibcall)
3007     Chain = DAG.getCALLSEQ_START(
3008         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3009
3010   SDValue RetAddrFrIdx;
3011   // Load return address for tail calls.
3012   if (isTailCall && FPDiff)
3013     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3014                                     Is64Bit, FPDiff, dl);
3015
3016   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3017   SmallVector<SDValue, 8> MemOpChains;
3018   SDValue StackPtr;
3019
3020   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3021   // of tail call optimization arguments are handle later.
3022   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3023   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3024     // Skip inalloca arguments, they have already been written.
3025     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3026     if (Flags.isInAlloca())
3027       continue;
3028
3029     CCValAssign &VA = ArgLocs[i];
3030     EVT RegVT = VA.getLocVT();
3031     SDValue Arg = OutVals[i];
3032     bool isByVal = Flags.isByVal();
3033
3034     // Promote the value if needed.
3035     switch (VA.getLocInfo()) {
3036     default: llvm_unreachable("Unknown loc info!");
3037     case CCValAssign::Full: break;
3038     case CCValAssign::SExt:
3039       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3040       break;
3041     case CCValAssign::ZExt:
3042       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3043       break;
3044     case CCValAssign::AExt:
3045       if (Arg.getValueType().isVector() &&
3046           Arg.getValueType().getScalarType() == MVT::i1)
3047         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3048       else if (RegVT.is128BitVector()) {
3049         // Special case: passing MMX values in XMM registers.
3050         Arg = DAG.getBitcast(MVT::i64, Arg);
3051         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3052         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3053       } else
3054         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3055       break;
3056     case CCValAssign::BCvt:
3057       Arg = DAG.getBitcast(RegVT, Arg);
3058       break;
3059     case CCValAssign::Indirect: {
3060       // Store the argument.
3061       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3062       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3063       Chain = DAG.getStore(
3064           Chain, dl, Arg, SpillSlot,
3065           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3066           false, false, 0);
3067       Arg = SpillSlot;
3068       break;
3069     }
3070     }
3071
3072     if (VA.isRegLoc()) {
3073       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3074       if (isVarArg && IsWin64) {
3075         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3076         // shadow reg if callee is a varargs function.
3077         unsigned ShadowReg = 0;
3078         switch (VA.getLocReg()) {
3079         case X86::XMM0: ShadowReg = X86::RCX; break;
3080         case X86::XMM1: ShadowReg = X86::RDX; break;
3081         case X86::XMM2: ShadowReg = X86::R8; break;
3082         case X86::XMM3: ShadowReg = X86::R9; break;
3083         }
3084         if (ShadowReg)
3085           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3086       }
3087     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3088       assert(VA.isMemLoc());
3089       if (!StackPtr.getNode())
3090         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3091                                       getPointerTy(DAG.getDataLayout()));
3092       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3093                                              dl, DAG, VA, Flags));
3094     }
3095   }
3096
3097   if (!MemOpChains.empty())
3098     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3099
3100   if (Subtarget->isPICStyleGOT()) {
3101     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3102     // GOT pointer.
3103     if (!isTailCall) {
3104       RegsToPass.push_back(std::make_pair(
3105           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3106                                           getPointerTy(DAG.getDataLayout()))));
3107     } else {
3108       // If we are tail calling and generating PIC/GOT style code load the
3109       // address of the callee into ECX. The value in ecx is used as target of
3110       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3111       // for tail calls on PIC/GOT architectures. Normally we would just put the
3112       // address of GOT into ebx and then call target@PLT. But for tail calls
3113       // ebx would be restored (since ebx is callee saved) before jumping to the
3114       // target@PLT.
3115
3116       // Note: The actual moving to ECX is done further down.
3117       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3118       if (G && !G->getGlobal()->hasLocalLinkage() &&
3119           G->getGlobal()->hasDefaultVisibility())
3120         Callee = LowerGlobalAddress(Callee, DAG);
3121       else if (isa<ExternalSymbolSDNode>(Callee))
3122         Callee = LowerExternalSymbol(Callee, DAG);
3123     }
3124   }
3125
3126   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3127     // From AMD64 ABI document:
3128     // For calls that may call functions that use varargs or stdargs
3129     // (prototype-less calls or calls to functions containing ellipsis (...) in
3130     // the declaration) %al is used as hidden argument to specify the number
3131     // of SSE registers used. The contents of %al do not need to match exactly
3132     // the number of registers, but must be an ubound on the number of SSE
3133     // registers used and is in the range 0 - 8 inclusive.
3134
3135     // Count the number of XMM registers allocated.
3136     static const MCPhysReg XMMArgRegs[] = {
3137       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3138       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3139     };
3140     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3141     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3142            && "SSE registers cannot be used when SSE is disabled");
3143
3144     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3145                                         DAG.getConstant(NumXMMRegs, dl,
3146                                                         MVT::i8)));
3147   }
3148
3149   if (isVarArg && IsMustTail) {
3150     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3151     for (const auto &F : Forwards) {
3152       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3153       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3154     }
3155   }
3156
3157   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3158   // don't need this because the eligibility check rejects calls that require
3159   // shuffling arguments passed in memory.
3160   if (!IsSibcall && isTailCall) {
3161     // Force all the incoming stack arguments to be loaded from the stack
3162     // before any new outgoing arguments are stored to the stack, because the
3163     // outgoing stack slots may alias the incoming argument stack slots, and
3164     // the alias isn't otherwise explicit. This is slightly more conservative
3165     // than necessary, because it means that each store effectively depends
3166     // on every argument instead of just those arguments it would clobber.
3167     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3168
3169     SmallVector<SDValue, 8> MemOpChains2;
3170     SDValue FIN;
3171     int FI = 0;
3172     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3173       CCValAssign &VA = ArgLocs[i];
3174       if (VA.isRegLoc())
3175         continue;
3176       assert(VA.isMemLoc());
3177       SDValue Arg = OutVals[i];
3178       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3179       // Skip inalloca arguments.  They don't require any work.
3180       if (Flags.isInAlloca())
3181         continue;
3182       // Create frame index.
3183       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3184       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3185       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3186       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3187
3188       if (Flags.isByVal()) {
3189         // Copy relative to framepointer.
3190         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3191         if (!StackPtr.getNode())
3192           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3193                                         getPointerTy(DAG.getDataLayout()));
3194         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3195                              StackPtr, Source);
3196
3197         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3198                                                          ArgChain,
3199                                                          Flags, DAG, dl));
3200       } else {
3201         // Store relative to framepointer.
3202         MemOpChains2.push_back(DAG.getStore(
3203             ArgChain, dl, Arg, FIN,
3204             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3205             false, false, 0));
3206       }
3207     }
3208
3209     if (!MemOpChains2.empty())
3210       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3211
3212     // Store the return address to the appropriate stack slot.
3213     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3214                                      getPointerTy(DAG.getDataLayout()),
3215                                      RegInfo->getSlotSize(), FPDiff, dl);
3216   }
3217
3218   // Build a sequence of copy-to-reg nodes chained together with token chain
3219   // and flag operands which copy the outgoing args into registers.
3220   SDValue InFlag;
3221   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3222     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3223                              RegsToPass[i].second, InFlag);
3224     InFlag = Chain.getValue(1);
3225   }
3226
3227   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3228     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3229     // In the 64-bit large code model, we have to make all calls
3230     // through a register, since the call instruction's 32-bit
3231     // pc-relative offset may not be large enough to hold the whole
3232     // address.
3233   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3234     // If the callee is a GlobalAddress node (quite common, every direct call
3235     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3236     // it.
3237     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3238
3239     // We should use extra load for direct calls to dllimported functions in
3240     // non-JIT mode.
3241     const GlobalValue *GV = G->getGlobal();
3242     if (!GV->hasDLLImportStorageClass()) {
3243       unsigned char OpFlags = 0;
3244       bool ExtraLoad = false;
3245       unsigned WrapperKind = ISD::DELETED_NODE;
3246
3247       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3248       // external symbols most go through the PLT in PIC mode.  If the symbol
3249       // has hidden or protected visibility, or if it is static or local, then
3250       // we don't need to use the PLT - we can directly call it.
3251       if (Subtarget->isTargetELF() &&
3252           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3253           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3254         OpFlags = X86II::MO_PLT;
3255       } else if (Subtarget->isPICStyleStubAny() &&
3256                  !GV->isStrongDefinitionForLinker() &&
3257                  (!Subtarget->getTargetTriple().isMacOSX() ||
3258                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3259         // PC-relative references to external symbols should go through $stub,
3260         // unless we're building with the leopard linker or later, which
3261         // automatically synthesizes these stubs.
3262         OpFlags = X86II::MO_DARWIN_STUB;
3263       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3264                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3265         // If the function is marked as non-lazy, generate an indirect call
3266         // which loads from the GOT directly. This avoids runtime overhead
3267         // at the cost of eager binding (and one extra byte of encoding).
3268         OpFlags = X86II::MO_GOTPCREL;
3269         WrapperKind = X86ISD::WrapperRIP;
3270         ExtraLoad = true;
3271       }
3272
3273       Callee = DAG.getTargetGlobalAddress(
3274           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3275
3276       // Add a wrapper if needed.
3277       if (WrapperKind != ISD::DELETED_NODE)
3278         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3279                              getPointerTy(DAG.getDataLayout()), Callee);
3280       // Add extra indirection if needed.
3281       if (ExtraLoad)
3282         Callee = DAG.getLoad(
3283             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3284             MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3285             false, 0);
3286     }
3287   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3288     unsigned char OpFlags = 0;
3289
3290     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3291     // external symbols should go through the PLT.
3292     if (Subtarget->isTargetELF() &&
3293         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3294       OpFlags = X86II::MO_PLT;
3295     } else if (Subtarget->isPICStyleStubAny() &&
3296                (!Subtarget->getTargetTriple().isMacOSX() ||
3297                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3298       // PC-relative references to external symbols should go through $stub,
3299       // unless we're building with the leopard linker or later, which
3300       // automatically synthesizes these stubs.
3301       OpFlags = X86II::MO_DARWIN_STUB;
3302     }
3303
3304     Callee = DAG.getTargetExternalSymbol(
3305         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3306   } else if (Subtarget->isTarget64BitILP32() &&
3307              Callee->getValueType(0) == MVT::i32) {
3308     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3309     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3310   }
3311
3312   // Returns a chain & a flag for retval copy to use.
3313   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3314   SmallVector<SDValue, 8> Ops;
3315
3316   if (!IsSibcall && isTailCall) {
3317     Chain = DAG.getCALLSEQ_END(Chain,
3318                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3319                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3320     InFlag = Chain.getValue(1);
3321   }
3322
3323   Ops.push_back(Chain);
3324   Ops.push_back(Callee);
3325
3326   if (isTailCall)
3327     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3328
3329   // Add argument registers to the end of the list so that they are known live
3330   // into the call.
3331   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3332     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3333                                   RegsToPass[i].second.getValueType()));
3334
3335   // Add a register mask operand representing the call-preserved registers.
3336   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3337   assert(Mask && "Missing call preserved mask for calling convention");
3338
3339   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3340   // the function clobbers all registers. If an exception is thrown, the runtime
3341   // will not restore CSRs.
3342   // FIXME: Model this more precisely so that we can register allocate across
3343   // the normal edge and spill and fill across the exceptional edge.
3344   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3345     const Function *CallerFn = MF.getFunction();
3346     EHPersonality Pers =
3347         CallerFn->hasPersonalityFn()
3348             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3349             : EHPersonality::Unknown;
3350     if (isMSVCEHPersonality(Pers))
3351       Mask = RegInfo->getNoPreservedMask();
3352   }
3353
3354   Ops.push_back(DAG.getRegisterMask(Mask));
3355
3356   if (InFlag.getNode())
3357     Ops.push_back(InFlag);
3358
3359   if (isTailCall) {
3360     // We used to do:
3361     //// If this is the first return lowered for this function, add the regs
3362     //// to the liveout set for the function.
3363     // This isn't right, although it's probably harmless on x86; liveouts
3364     // should be computed from returns not tail calls.  Consider a void
3365     // function making a tail call to a function returning int.
3366     MF.getFrameInfo()->setHasTailCall();
3367     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3368   }
3369
3370   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3371   InFlag = Chain.getValue(1);
3372
3373   // Create the CALLSEQ_END node.
3374   unsigned NumBytesForCalleeToPop;
3375   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3376                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3377     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3378   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3379            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3380            SR == StackStructReturn)
3381     // If this is a call to a struct-return function, the callee
3382     // pops the hidden struct pointer, so we have to push it back.
3383     // This is common for Darwin/X86, Linux & Mingw32 targets.
3384     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3385     NumBytesForCalleeToPop = 4;
3386   else
3387     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3388
3389   // Returns a flag for retval copy to use.
3390   if (!IsSibcall) {
3391     Chain = DAG.getCALLSEQ_END(Chain,
3392                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3393                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3394                                                      true),
3395                                InFlag, dl);
3396     InFlag = Chain.getValue(1);
3397   }
3398
3399   // Handle result values, copying them out of physregs into vregs that we
3400   // return.
3401   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3402                          Ins, dl, DAG, InVals);
3403 }
3404
3405 //===----------------------------------------------------------------------===//
3406 //                Fast Calling Convention (tail call) implementation
3407 //===----------------------------------------------------------------------===//
3408
3409 //  Like std call, callee cleans arguments, convention except that ECX is
3410 //  reserved for storing the tail called function address. Only 2 registers are
3411 //  free for argument passing (inreg). Tail call optimization is performed
3412 //  provided:
3413 //                * tailcallopt is enabled
3414 //                * caller/callee are fastcc
3415 //  On X86_64 architecture with GOT-style position independent code only local
3416 //  (within module) calls are supported at the moment.
3417 //  To keep the stack aligned according to platform abi the function
3418 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3419 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3420 //  If a tail called function callee has more arguments than the caller the
3421 //  caller needs to make sure that there is room to move the RETADDR to. This is
3422 //  achieved by reserving an area the size of the argument delta right after the
3423 //  original RETADDR, but before the saved framepointer or the spilled registers
3424 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3425 //  stack layout:
3426 //    arg1
3427 //    arg2
3428 //    RETADDR
3429 //    [ new RETADDR
3430 //      move area ]
3431 //    (possible EBP)
3432 //    ESI
3433 //    EDI
3434 //    local1 ..
3435
3436 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3437 /// requirement.
3438 unsigned
3439 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3440                                                SelectionDAG& DAG) const {
3441   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3442   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3443   unsigned StackAlignment = TFI.getStackAlignment();
3444   uint64_t AlignMask = StackAlignment - 1;
3445   int64_t Offset = StackSize;
3446   unsigned SlotSize = RegInfo->getSlotSize();
3447   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3448     // Number smaller than 12 so just add the difference.
3449     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3450   } else {
3451     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3452     Offset = ((~AlignMask) & Offset) + StackAlignment +
3453       (StackAlignment-SlotSize);
3454   }
3455   return Offset;
3456 }
3457
3458 /// Return true if the given stack call argument is already available in the
3459 /// same position (relatively) of the caller's incoming argument stack.
3460 static
3461 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3462                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3463                          const X86InstrInfo *TII) {
3464   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3465   int FI = INT_MAX;
3466   if (Arg.getOpcode() == ISD::CopyFromReg) {
3467     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3468     if (!TargetRegisterInfo::isVirtualRegister(VR))
3469       return false;
3470     MachineInstr *Def = MRI->getVRegDef(VR);
3471     if (!Def)
3472       return false;
3473     if (!Flags.isByVal()) {
3474       if (!TII->isLoadFromStackSlot(Def, FI))
3475         return false;
3476     } else {
3477       unsigned Opcode = Def->getOpcode();
3478       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3479            Opcode == X86::LEA64_32r) &&
3480           Def->getOperand(1).isFI()) {
3481         FI = Def->getOperand(1).getIndex();
3482         Bytes = Flags.getByValSize();
3483       } else
3484         return false;
3485     }
3486   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3487     if (Flags.isByVal())
3488       // ByVal argument is passed in as a pointer but it's now being
3489       // dereferenced. e.g.
3490       // define @foo(%struct.X* %A) {
3491       //   tail call @bar(%struct.X* byval %A)
3492       // }
3493       return false;
3494     SDValue Ptr = Ld->getBasePtr();
3495     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3496     if (!FINode)
3497       return false;
3498     FI = FINode->getIndex();
3499   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3500     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3501     FI = FINode->getIndex();
3502     Bytes = Flags.getByValSize();
3503   } else
3504     return false;
3505
3506   assert(FI != INT_MAX);
3507   if (!MFI->isFixedObjectIndex(FI))
3508     return false;
3509   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3510 }
3511
3512 /// Check whether the call is eligible for tail call optimization. Targets
3513 /// that want to do tail call optimization should implement this function.
3514 bool
3515 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3516                                                      CallingConv::ID CalleeCC,
3517                                                      bool isVarArg,
3518                                                      bool isCalleeStructRet,
3519                                                      bool isCallerStructRet,
3520                                                      Type *RetTy,
3521                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3522                                     const SmallVectorImpl<SDValue> &OutVals,
3523                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3524                                                      SelectionDAG &DAG) const {
3525   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3526     return false;
3527
3528   // If -tailcallopt is specified, make fastcc functions tail-callable.
3529   const MachineFunction &MF = DAG.getMachineFunction();
3530   const Function *CallerF = MF.getFunction();
3531
3532   // If the function return type is x86_fp80 and the callee return type is not,
3533   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3534   // perform a tailcall optimization here.
3535   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3536     return false;
3537
3538   CallingConv::ID CallerCC = CallerF->getCallingConv();
3539   bool CCMatch = CallerCC == CalleeCC;
3540   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3541   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3542
3543   // Win64 functions have extra shadow space for argument homing. Don't do the
3544   // sibcall if the caller and callee have mismatched expectations for this
3545   // space.
3546   if (IsCalleeWin64 != IsCallerWin64)
3547     return false;
3548
3549   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3550     if (IsTailCallConvention(CalleeCC) && CCMatch)
3551       return true;
3552     return false;
3553   }
3554
3555   // Look for obvious safe cases to perform tail call optimization that do not
3556   // require ABI changes. This is what gcc calls sibcall.
3557
3558   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3559   // emit a special epilogue.
3560   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3561   if (RegInfo->needsStackRealignment(MF))
3562     return false;
3563
3564   // Also avoid sibcall optimization if either caller or callee uses struct
3565   // return semantics.
3566   if (isCalleeStructRet || isCallerStructRet)
3567     return false;
3568
3569   // An stdcall/thiscall caller is expected to clean up its arguments; the
3570   // callee isn't going to do that.
3571   // FIXME: this is more restrictive than needed. We could produce a tailcall
3572   // when the stack adjustment matches. For example, with a thiscall that takes
3573   // only one argument.
3574   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3575                    CallerCC == CallingConv::X86_ThisCall))
3576     return false;
3577
3578   // Do not sibcall optimize vararg calls unless all arguments are passed via
3579   // registers.
3580   if (isVarArg && !Outs.empty()) {
3581
3582     // Optimizing for varargs on Win64 is unlikely to be safe without
3583     // additional testing.
3584     if (IsCalleeWin64 || IsCallerWin64)
3585       return false;
3586
3587     SmallVector<CCValAssign, 16> ArgLocs;
3588     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3589                    *DAG.getContext());
3590
3591     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3592     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3593       if (!ArgLocs[i].isRegLoc())
3594         return false;
3595   }
3596
3597   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3598   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3599   // this into a sibcall.
3600   bool Unused = false;
3601   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3602     if (!Ins[i].Used) {
3603       Unused = true;
3604       break;
3605     }
3606   }
3607   if (Unused) {
3608     SmallVector<CCValAssign, 16> RVLocs;
3609     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3610                    *DAG.getContext());
3611     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3612     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3613       CCValAssign &VA = RVLocs[i];
3614       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3615         return false;
3616     }
3617   }
3618
3619   // If the calling conventions do not match, then we'd better make sure the
3620   // results are returned in the same way as what the caller expects.
3621   if (!CCMatch) {
3622     SmallVector<CCValAssign, 16> RVLocs1;
3623     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3624                     *DAG.getContext());
3625     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3626
3627     SmallVector<CCValAssign, 16> RVLocs2;
3628     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3629                     *DAG.getContext());
3630     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3631
3632     if (RVLocs1.size() != RVLocs2.size())
3633       return false;
3634     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3635       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3636         return false;
3637       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3638         return false;
3639       if (RVLocs1[i].isRegLoc()) {
3640         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3641           return false;
3642       } else {
3643         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3644           return false;
3645       }
3646     }
3647   }
3648
3649   // If the callee takes no arguments then go on to check the results of the
3650   // call.
3651   if (!Outs.empty()) {
3652     // Check if stack adjustment is needed. For now, do not do this if any
3653     // argument is passed on the stack.
3654     SmallVector<CCValAssign, 16> ArgLocs;
3655     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3656                    *DAG.getContext());
3657
3658     // Allocate shadow area for Win64
3659     if (IsCalleeWin64)
3660       CCInfo.AllocateStack(32, 8);
3661
3662     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3663     if (CCInfo.getNextStackOffset()) {
3664       MachineFunction &MF = DAG.getMachineFunction();
3665       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3666         return false;
3667
3668       // Check if the arguments are already laid out in the right way as
3669       // the caller's fixed stack objects.
3670       MachineFrameInfo *MFI = MF.getFrameInfo();
3671       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3672       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3673       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3674         CCValAssign &VA = ArgLocs[i];
3675         SDValue Arg = OutVals[i];
3676         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3677         if (VA.getLocInfo() == CCValAssign::Indirect)
3678           return false;
3679         if (!VA.isRegLoc()) {
3680           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3681                                    MFI, MRI, TII))
3682             return false;
3683         }
3684       }
3685     }
3686
3687     // If the tailcall address may be in a register, then make sure it's
3688     // possible to register allocate for it. In 32-bit, the call address can
3689     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3690     // callee-saved registers are restored. These happen to be the same
3691     // registers used to pass 'inreg' arguments so watch out for those.
3692     if (!Subtarget->is64Bit() &&
3693         ((!isa<GlobalAddressSDNode>(Callee) &&
3694           !isa<ExternalSymbolSDNode>(Callee)) ||
3695          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3696       unsigned NumInRegs = 0;
3697       // In PIC we need an extra register to formulate the address computation
3698       // for the callee.
3699       unsigned MaxInRegs =
3700         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3701
3702       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3703         CCValAssign &VA = ArgLocs[i];
3704         if (!VA.isRegLoc())
3705           continue;
3706         unsigned Reg = VA.getLocReg();
3707         switch (Reg) {
3708         default: break;
3709         case X86::EAX: case X86::EDX: case X86::ECX:
3710           if (++NumInRegs == MaxInRegs)
3711             return false;
3712           break;
3713         }
3714       }
3715     }
3716   }
3717
3718   return true;
3719 }
3720
3721 FastISel *
3722 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3723                                   const TargetLibraryInfo *libInfo) const {
3724   return X86::createFastISel(funcInfo, libInfo);
3725 }
3726
3727 //===----------------------------------------------------------------------===//
3728 //                           Other Lowering Hooks
3729 //===----------------------------------------------------------------------===//
3730
3731 static bool MayFoldLoad(SDValue Op) {
3732   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3733 }
3734
3735 static bool MayFoldIntoStore(SDValue Op) {
3736   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3737 }
3738
3739 static bool isTargetShuffle(unsigned Opcode) {
3740   switch(Opcode) {
3741   default: return false;
3742   case X86ISD::BLENDI:
3743   case X86ISD::PSHUFB:
3744   case X86ISD::PSHUFD:
3745   case X86ISD::PSHUFHW:
3746   case X86ISD::PSHUFLW:
3747   case X86ISD::SHUFP:
3748   case X86ISD::PALIGNR:
3749   case X86ISD::MOVLHPS:
3750   case X86ISD::MOVLHPD:
3751   case X86ISD::MOVHLPS:
3752   case X86ISD::MOVLPS:
3753   case X86ISD::MOVLPD:
3754   case X86ISD::MOVSHDUP:
3755   case X86ISD::MOVSLDUP:
3756   case X86ISD::MOVDDUP:
3757   case X86ISD::MOVSS:
3758   case X86ISD::MOVSD:
3759   case X86ISD::UNPCKL:
3760   case X86ISD::UNPCKH:
3761   case X86ISD::VPERMILPI:
3762   case X86ISD::VPERM2X128:
3763   case X86ISD::VPERMI:
3764     return true;
3765   }
3766 }
3767
3768 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3769                                     SDValue V1, unsigned TargetMask,
3770                                     SelectionDAG &DAG) {
3771   switch(Opc) {
3772   default: llvm_unreachable("Unknown x86 shuffle node");
3773   case X86ISD::PSHUFD:
3774   case X86ISD::PSHUFHW:
3775   case X86ISD::PSHUFLW:
3776   case X86ISD::VPERMILPI:
3777   case X86ISD::VPERMI:
3778     return DAG.getNode(Opc, dl, VT, V1,
3779                        DAG.getConstant(TargetMask, dl, MVT::i8));
3780   }
3781 }
3782
3783 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3784                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3785   switch(Opc) {
3786   default: llvm_unreachable("Unknown x86 shuffle node");
3787   case X86ISD::MOVLHPS:
3788   case X86ISD::MOVLHPD:
3789   case X86ISD::MOVHLPS:
3790   case X86ISD::MOVLPS:
3791   case X86ISD::MOVLPD:
3792   case X86ISD::MOVSS:
3793   case X86ISD::MOVSD:
3794   case X86ISD::UNPCKL:
3795   case X86ISD::UNPCKH:
3796     return DAG.getNode(Opc, dl, VT, V1, V2);
3797   }
3798 }
3799
3800 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3801   MachineFunction &MF = DAG.getMachineFunction();
3802   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3803   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3804   int ReturnAddrIndex = FuncInfo->getRAIndex();
3805
3806   if (ReturnAddrIndex == 0) {
3807     // Set up a frame object for the return address.
3808     unsigned SlotSize = RegInfo->getSlotSize();
3809     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3810                                                            -(int64_t)SlotSize,
3811                                                            false);
3812     FuncInfo->setRAIndex(ReturnAddrIndex);
3813   }
3814
3815   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3816 }
3817
3818 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3819                                        bool hasSymbolicDisplacement) {
3820   // Offset should fit into 32 bit immediate field.
3821   if (!isInt<32>(Offset))
3822     return false;
3823
3824   // If we don't have a symbolic displacement - we don't have any extra
3825   // restrictions.
3826   if (!hasSymbolicDisplacement)
3827     return true;
3828
3829   // FIXME: Some tweaks might be needed for medium code model.
3830   if (M != CodeModel::Small && M != CodeModel::Kernel)
3831     return false;
3832
3833   // For small code model we assume that latest object is 16MB before end of 31
3834   // bits boundary. We may also accept pretty large negative constants knowing
3835   // that all objects are in the positive half of address space.
3836   if (M == CodeModel::Small && Offset < 16*1024*1024)
3837     return true;
3838
3839   // For kernel code model we know that all object resist in the negative half
3840   // of 32bits address space. We may not accept negative offsets, since they may
3841   // be just off and we may accept pretty large positive ones.
3842   if (M == CodeModel::Kernel && Offset >= 0)
3843     return true;
3844
3845   return false;
3846 }
3847
3848 /// Determines whether the callee is required to pop its own arguments.
3849 /// Callee pop is necessary to support tail calls.
3850 bool X86::isCalleePop(CallingConv::ID CallingConv,
3851                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3852   switch (CallingConv) {
3853   default:
3854     return false;
3855   case CallingConv::X86_StdCall:
3856   case CallingConv::X86_FastCall:
3857   case CallingConv::X86_ThisCall:
3858     return !is64Bit;
3859   case CallingConv::Fast:
3860   case CallingConv::GHC:
3861   case CallingConv::HiPE:
3862     if (IsVarArg)
3863       return false;
3864     return TailCallOpt;
3865   }
3866 }
3867
3868 /// \brief Return true if the condition is an unsigned comparison operation.
3869 static bool isX86CCUnsigned(unsigned X86CC) {
3870   switch (X86CC) {
3871   default: llvm_unreachable("Invalid integer condition!");
3872   case X86::COND_E:     return true;
3873   case X86::COND_G:     return false;
3874   case X86::COND_GE:    return false;
3875   case X86::COND_L:     return false;
3876   case X86::COND_LE:    return false;
3877   case X86::COND_NE:    return true;
3878   case X86::COND_B:     return true;
3879   case X86::COND_A:     return true;
3880   case X86::COND_BE:    return true;
3881   case X86::COND_AE:    return true;
3882   }
3883   llvm_unreachable("covered switch fell through?!");
3884 }
3885
3886 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3887 /// condition code, returning the condition code and the LHS/RHS of the
3888 /// comparison to make.
3889 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3890                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3891   if (!isFP) {
3892     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3893       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3894         // X > -1   -> X == 0, jump !sign.
3895         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3896         return X86::COND_NS;
3897       }
3898       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3899         // X < 0   -> X == 0, jump on sign.
3900         return X86::COND_S;
3901       }
3902       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3903         // X < 1   -> X <= 0
3904         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3905         return X86::COND_LE;
3906       }
3907     }
3908
3909     switch (SetCCOpcode) {
3910     default: llvm_unreachable("Invalid integer condition!");
3911     case ISD::SETEQ:  return X86::COND_E;
3912     case ISD::SETGT:  return X86::COND_G;
3913     case ISD::SETGE:  return X86::COND_GE;
3914     case ISD::SETLT:  return X86::COND_L;
3915     case ISD::SETLE:  return X86::COND_LE;
3916     case ISD::SETNE:  return X86::COND_NE;
3917     case ISD::SETULT: return X86::COND_B;
3918     case ISD::SETUGT: return X86::COND_A;
3919     case ISD::SETULE: return X86::COND_BE;
3920     case ISD::SETUGE: return X86::COND_AE;
3921     }
3922   }
3923
3924   // First determine if it is required or is profitable to flip the operands.
3925
3926   // If LHS is a foldable load, but RHS is not, flip the condition.
3927   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3928       !ISD::isNON_EXTLoad(RHS.getNode())) {
3929     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3930     std::swap(LHS, RHS);
3931   }
3932
3933   switch (SetCCOpcode) {
3934   default: break;
3935   case ISD::SETOLT:
3936   case ISD::SETOLE:
3937   case ISD::SETUGT:
3938   case ISD::SETUGE:
3939     std::swap(LHS, RHS);
3940     break;
3941   }
3942
3943   // On a floating point condition, the flags are set as follows:
3944   // ZF  PF  CF   op
3945   //  0 | 0 | 0 | X > Y
3946   //  0 | 0 | 1 | X < Y
3947   //  1 | 0 | 0 | X == Y
3948   //  1 | 1 | 1 | unordered
3949   switch (SetCCOpcode) {
3950   default: llvm_unreachable("Condcode should be pre-legalized away");
3951   case ISD::SETUEQ:
3952   case ISD::SETEQ:   return X86::COND_E;
3953   case ISD::SETOLT:              // flipped
3954   case ISD::SETOGT:
3955   case ISD::SETGT:   return X86::COND_A;
3956   case ISD::SETOLE:              // flipped
3957   case ISD::SETOGE:
3958   case ISD::SETGE:   return X86::COND_AE;
3959   case ISD::SETUGT:              // flipped
3960   case ISD::SETULT:
3961   case ISD::SETLT:   return X86::COND_B;
3962   case ISD::SETUGE:              // flipped
3963   case ISD::SETULE:
3964   case ISD::SETLE:   return X86::COND_BE;
3965   case ISD::SETONE:
3966   case ISD::SETNE:   return X86::COND_NE;
3967   case ISD::SETUO:   return X86::COND_P;
3968   case ISD::SETO:    return X86::COND_NP;
3969   case ISD::SETOEQ:
3970   case ISD::SETUNE:  return X86::COND_INVALID;
3971   }
3972 }
3973
3974 /// Is there a floating point cmov for the specific X86 condition code?
3975 /// Current x86 isa includes the following FP cmov instructions:
3976 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3977 static bool hasFPCMov(unsigned X86CC) {
3978   switch (X86CC) {
3979   default:
3980     return false;
3981   case X86::COND_B:
3982   case X86::COND_BE:
3983   case X86::COND_E:
3984   case X86::COND_P:
3985   case X86::COND_A:
3986   case X86::COND_AE:
3987   case X86::COND_NE:
3988   case X86::COND_NP:
3989     return true;
3990   }
3991 }
3992
3993 /// Returns true if the target can instruction select the
3994 /// specified FP immediate natively. If false, the legalizer will
3995 /// materialize the FP immediate as a load from a constant pool.
3996 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3997   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3998     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3999       return true;
4000   }
4001   return false;
4002 }
4003
4004 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4005                                               ISD::LoadExtType ExtTy,
4006                                               EVT NewVT) const {
4007   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4008   // relocation target a movq or addq instruction: don't let the load shrink.
4009   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4010   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4011     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4012       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4013   return true;
4014 }
4015
4016 /// \brief Returns true if it is beneficial to convert a load of a constant
4017 /// to just the constant itself.
4018 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4019                                                           Type *Ty) const {
4020   assert(Ty->isIntegerTy());
4021
4022   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4023   if (BitSize == 0 || BitSize > 64)
4024     return false;
4025   return true;
4026 }
4027
4028 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4029                                                 unsigned Index) const {
4030   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4031     return false;
4032
4033   return (Index == 0 || Index == ResVT.getVectorNumElements());
4034 }
4035
4036 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4037   // Speculate cttz only if we can directly use TZCNT.
4038   return Subtarget->hasBMI();
4039 }
4040
4041 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4042   // Speculate ctlz only if we can directly use LZCNT.
4043   return Subtarget->hasLZCNT();
4044 }
4045
4046 /// Return true if every element in Mask, beginning
4047 /// from position Pos and ending in Pos+Size is undef.
4048 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4049   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4050     if (0 <= Mask[i])
4051       return false;
4052   return true;
4053 }
4054
4055 /// Return true if Val is undef or if its value falls within the
4056 /// specified range (L, H].
4057 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4058   return (Val < 0) || (Val >= Low && Val < Hi);
4059 }
4060
4061 /// Val is either less than zero (undef) or equal to the specified value.
4062 static bool isUndefOrEqual(int Val, int CmpVal) {
4063   return (Val < 0 || Val == CmpVal);
4064 }
4065
4066 /// Return true if every element in Mask, beginning
4067 /// from position Pos and ending in Pos+Size, falls within the specified
4068 /// sequential range (Low, Low+Size]. or is undef.
4069 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4070                                        unsigned Pos, unsigned Size, int Low) {
4071   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4072     if (!isUndefOrEqual(Mask[i], Low))
4073       return false;
4074   return true;
4075 }
4076
4077 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4078 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4079 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4080   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4081   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4082     return false;
4083
4084   // The index should be aligned on a vecWidth-bit boundary.
4085   uint64_t Index =
4086     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4087
4088   MVT VT = N->getSimpleValueType(0);
4089   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4090   bool Result = (Index * ElSize) % vecWidth == 0;
4091
4092   return Result;
4093 }
4094
4095 /// Return true if the specified INSERT_SUBVECTOR
4096 /// operand specifies a subvector insert that is suitable for input to
4097 /// insertion of 128 or 256-bit subvectors
4098 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4099   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4100   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4101     return false;
4102   // The index should be aligned on a vecWidth-bit boundary.
4103   uint64_t Index =
4104     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4105
4106   MVT VT = N->getSimpleValueType(0);
4107   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4108   bool Result = (Index * ElSize) % vecWidth == 0;
4109
4110   return Result;
4111 }
4112
4113 bool X86::isVINSERT128Index(SDNode *N) {
4114   return isVINSERTIndex(N, 128);
4115 }
4116
4117 bool X86::isVINSERT256Index(SDNode *N) {
4118   return isVINSERTIndex(N, 256);
4119 }
4120
4121 bool X86::isVEXTRACT128Index(SDNode *N) {
4122   return isVEXTRACTIndex(N, 128);
4123 }
4124
4125 bool X86::isVEXTRACT256Index(SDNode *N) {
4126   return isVEXTRACTIndex(N, 256);
4127 }
4128
4129 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4130   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4131   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4132     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4133
4134   uint64_t Index =
4135     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4136
4137   MVT VecVT = N->getOperand(0).getSimpleValueType();
4138   MVT ElVT = VecVT.getVectorElementType();
4139
4140   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4141   return Index / NumElemsPerChunk;
4142 }
4143
4144 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4145   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4146   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4147     llvm_unreachable("Illegal insert subvector for VINSERT");
4148
4149   uint64_t Index =
4150     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4151
4152   MVT VecVT = N->getSimpleValueType(0);
4153   MVT ElVT = VecVT.getVectorElementType();
4154
4155   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4156   return Index / NumElemsPerChunk;
4157 }
4158
4159 /// Return the appropriate immediate to extract the specified
4160 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4161 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4162   return getExtractVEXTRACTImmediate(N, 128);
4163 }
4164
4165 /// Return the appropriate immediate to extract the specified
4166 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4167 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4168   return getExtractVEXTRACTImmediate(N, 256);
4169 }
4170
4171 /// Return the appropriate immediate to insert at the specified
4172 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4173 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4174   return getInsertVINSERTImmediate(N, 128);
4175 }
4176
4177 /// Return the appropriate immediate to insert at the specified
4178 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4179 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4180   return getInsertVINSERTImmediate(N, 256);
4181 }
4182
4183 /// Returns true if Elt is a constant integer zero
4184 static bool isZero(SDValue V) {
4185   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4186   return C && C->isNullValue();
4187 }
4188
4189 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4190 bool X86::isZeroNode(SDValue Elt) {
4191   if (isZero(Elt))
4192     return true;
4193   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4194     return CFP->getValueAPF().isPosZero();
4195   return false;
4196 }
4197
4198 /// Returns a vector of specified type with all zero elements.
4199 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4200                              SelectionDAG &DAG, SDLoc dl) {
4201   assert(VT.isVector() && "Expected a vector type");
4202
4203   // Always build SSE zero vectors as <4 x i32> bitcasted
4204   // to their dest type. This ensures they get CSE'd.
4205   SDValue Vec;
4206   if (VT.is128BitVector()) {  // SSE
4207     if (Subtarget->hasSSE2()) {  // SSE2
4208       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4209       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4210     } else { // SSE1
4211       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4212       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4213     }
4214   } else if (VT.is256BitVector()) { // AVX
4215     if (Subtarget->hasInt256()) { // AVX2
4216       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4217       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4218       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4219     } else {
4220       // 256-bit logic and arithmetic instructions in AVX are all
4221       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4222       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4223       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4224       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4225     }
4226   } else if (VT.is512BitVector()) { // AVX-512
4227       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4228       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4229                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4230       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4231   } else if (VT.getScalarType() == MVT::i1) {
4232
4233     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4234             && "Unexpected vector type");
4235     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4236             && "Unexpected vector type");
4237     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4238     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4239     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4240   } else
4241     llvm_unreachable("Unexpected vector type");
4242
4243   return DAG.getBitcast(VT, Vec);
4244 }
4245
4246 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4247                                 SelectionDAG &DAG, SDLoc dl,
4248                                 unsigned vectorWidth) {
4249   assert((vectorWidth == 128 || vectorWidth == 256) &&
4250          "Unsupported vector width");
4251   EVT VT = Vec.getValueType();
4252   EVT ElVT = VT.getVectorElementType();
4253   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4254   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4255                                   VT.getVectorNumElements()/Factor);
4256
4257   // Extract from UNDEF is UNDEF.
4258   if (Vec.getOpcode() == ISD::UNDEF)
4259     return DAG.getUNDEF(ResultVT);
4260
4261   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4262   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4263
4264   // This is the index of the first element of the vectorWidth-bit chunk
4265   // we want.
4266   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4267                                * ElemsPerChunk);
4268
4269   // If the input is a buildvector just emit a smaller one.
4270   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4271     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4272                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4273                                     ElemsPerChunk));
4274
4275   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4276   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4277 }
4278
4279 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4280 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4281 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4282 /// instructions or a simple subregister reference. Idx is an index in the
4283 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4284 /// lowering EXTRACT_VECTOR_ELT operations easier.
4285 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4286                                    SelectionDAG &DAG, SDLoc dl) {
4287   assert((Vec.getValueType().is256BitVector() ||
4288           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4289   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4290 }
4291
4292 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4293 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4294                                    SelectionDAG &DAG, SDLoc dl) {
4295   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4296   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4297 }
4298
4299 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4300                                unsigned IdxVal, SelectionDAG &DAG,
4301                                SDLoc dl, unsigned vectorWidth) {
4302   assert((vectorWidth == 128 || vectorWidth == 256) &&
4303          "Unsupported vector width");
4304   // Inserting UNDEF is Result
4305   if (Vec.getOpcode() == ISD::UNDEF)
4306     return Result;
4307   EVT VT = Vec.getValueType();
4308   EVT ElVT = VT.getVectorElementType();
4309   EVT ResultVT = Result.getValueType();
4310
4311   // Insert the relevant vectorWidth bits.
4312   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4313
4314   // This is the index of the first element of the vectorWidth-bit chunk
4315   // we want.
4316   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4317                                * ElemsPerChunk);
4318
4319   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4320   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4321 }
4322
4323 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4324 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4325 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4326 /// simple superregister reference.  Idx is an index in the 128 bits
4327 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4328 /// lowering INSERT_VECTOR_ELT operations easier.
4329 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4330                                   SelectionDAG &DAG, SDLoc dl) {
4331   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4332
4333   // For insertion into the zero index (low half) of a 256-bit vector, it is
4334   // more efficient to generate a blend with immediate instead of an insert*128.
4335   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4336   // extend the subvector to the size of the result vector. Make sure that
4337   // we are not recursing on that node by checking for undef here.
4338   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4339       Result.getOpcode() != ISD::UNDEF) {
4340     EVT ResultVT = Result.getValueType();
4341     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4342     SDValue Undef = DAG.getUNDEF(ResultVT);
4343     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4344                                  Vec, ZeroIndex);
4345
4346     // The blend instruction, and therefore its mask, depend on the data type.
4347     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4348     if (ScalarType.isFloatingPoint()) {
4349       // Choose either vblendps (float) or vblendpd (double).
4350       unsigned ScalarSize = ScalarType.getSizeInBits();
4351       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4352       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4353       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4354       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4355     }
4356
4357     const X86Subtarget &Subtarget =
4358     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4359
4360     // AVX2 is needed for 256-bit integer blend support.
4361     // Integers must be cast to 32-bit because there is only vpblendd;
4362     // vpblendw can't be used for this because it has a handicapped mask.
4363
4364     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4365     // is still more efficient than using the wrong domain vinsertf128 that
4366     // will be created by InsertSubVector().
4367     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4368
4369     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4370     Vec256 = DAG.getBitcast(CastVT, Vec256);
4371     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4372     return DAG.getBitcast(ResultVT, Vec256);
4373   }
4374
4375   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4376 }
4377
4378 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4379                                   SelectionDAG &DAG, SDLoc dl) {
4380   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4381   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4382 }
4383
4384 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4385 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4386 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4387 /// large BUILD_VECTORS.
4388 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4389                                    unsigned NumElems, SelectionDAG &DAG,
4390                                    SDLoc dl) {
4391   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4392   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4393 }
4394
4395 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4396                                    unsigned NumElems, SelectionDAG &DAG,
4397                                    SDLoc dl) {
4398   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4399   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4400 }
4401
4402 /// Returns a vector of specified type with all bits set.
4403 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4404 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4405 /// Then bitcast to their original type, ensuring they get CSE'd.
4406 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4407                              SDLoc dl) {
4408   assert(VT.isVector() && "Expected a vector type");
4409
4410   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4411   SDValue Vec;
4412   if (VT.is256BitVector()) {
4413     if (HasInt256) { // AVX2
4414       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4415       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4416     } else { // AVX
4417       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4418       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4419     }
4420   } else if (VT.is128BitVector()) {
4421     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4422   } else
4423     llvm_unreachable("Unexpected vector type");
4424
4425   return DAG.getBitcast(VT, Vec);
4426 }
4427
4428 /// Returns a vector_shuffle node for an unpackl operation.
4429 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4430                           SDValue V2) {
4431   unsigned NumElems = VT.getVectorNumElements();
4432   SmallVector<int, 8> Mask;
4433   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4434     Mask.push_back(i);
4435     Mask.push_back(i + NumElems);
4436   }
4437   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4438 }
4439
4440 /// Returns a vector_shuffle node for an unpackh operation.
4441 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4442                           SDValue V2) {
4443   unsigned NumElems = VT.getVectorNumElements();
4444   SmallVector<int, 8> Mask;
4445   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4446     Mask.push_back(i + Half);
4447     Mask.push_back(i + NumElems + Half);
4448   }
4449   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4450 }
4451
4452 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4453 /// This produces a shuffle where the low element of V2 is swizzled into the
4454 /// zero/undef vector, landing at element Idx.
4455 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4456 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4457                                            bool IsZero,
4458                                            const X86Subtarget *Subtarget,
4459                                            SelectionDAG &DAG) {
4460   MVT VT = V2.getSimpleValueType();
4461   SDValue V1 = IsZero
4462     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4463   unsigned NumElems = VT.getVectorNumElements();
4464   SmallVector<int, 16> MaskVec;
4465   for (unsigned i = 0; i != NumElems; ++i)
4466     // If this is the insertion idx, put the low elt of V2 here.
4467     MaskVec.push_back(i == Idx ? NumElems : i);
4468   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4469 }
4470
4471 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4472 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4473 /// uses one source. Note that this will set IsUnary for shuffles which use a
4474 /// single input multiple times, and in those cases it will
4475 /// adjust the mask to only have indices within that single input.
4476 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4477 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4478                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4479   unsigned NumElems = VT.getVectorNumElements();
4480   SDValue ImmN;
4481
4482   IsUnary = false;
4483   bool IsFakeUnary = false;
4484   switch(N->getOpcode()) {
4485   case X86ISD::BLENDI:
4486     ImmN = N->getOperand(N->getNumOperands()-1);
4487     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4488     break;
4489   case X86ISD::SHUFP:
4490     ImmN = N->getOperand(N->getNumOperands()-1);
4491     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4492     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4493     break;
4494   case X86ISD::UNPCKH:
4495     DecodeUNPCKHMask(VT, Mask);
4496     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4497     break;
4498   case X86ISD::UNPCKL:
4499     DecodeUNPCKLMask(VT, Mask);
4500     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4501     break;
4502   case X86ISD::MOVHLPS:
4503     DecodeMOVHLPSMask(NumElems, Mask);
4504     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4505     break;
4506   case X86ISD::MOVLHPS:
4507     DecodeMOVLHPSMask(NumElems, Mask);
4508     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4509     break;
4510   case X86ISD::PALIGNR:
4511     ImmN = N->getOperand(N->getNumOperands()-1);
4512     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4513     break;
4514   case X86ISD::PSHUFD:
4515   case X86ISD::VPERMILPI:
4516     ImmN = N->getOperand(N->getNumOperands()-1);
4517     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4518     IsUnary = true;
4519     break;
4520   case X86ISD::PSHUFHW:
4521     ImmN = N->getOperand(N->getNumOperands()-1);
4522     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4523     IsUnary = true;
4524     break;
4525   case X86ISD::PSHUFLW:
4526     ImmN = N->getOperand(N->getNumOperands()-1);
4527     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4528     IsUnary = true;
4529     break;
4530   case X86ISD::PSHUFB: {
4531     IsUnary = true;
4532     SDValue MaskNode = N->getOperand(1);
4533     while (MaskNode->getOpcode() == ISD::BITCAST)
4534       MaskNode = MaskNode->getOperand(0);
4535
4536     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4537       // If we have a build-vector, then things are easy.
4538       EVT VT = MaskNode.getValueType();
4539       assert(VT.isVector() &&
4540              "Can't produce a non-vector with a build_vector!");
4541       if (!VT.isInteger())
4542         return false;
4543
4544       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4545
4546       SmallVector<uint64_t, 32> RawMask;
4547       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4548         SDValue Op = MaskNode->getOperand(i);
4549         if (Op->getOpcode() == ISD::UNDEF) {
4550           RawMask.push_back((uint64_t)SM_SentinelUndef);
4551           continue;
4552         }
4553         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4554         if (!CN)
4555           return false;
4556         APInt MaskElement = CN->getAPIntValue();
4557
4558         // We now have to decode the element which could be any integer size and
4559         // extract each byte of it.
4560         for (int j = 0; j < NumBytesPerElement; ++j) {
4561           // Note that this is x86 and so always little endian: the low byte is
4562           // the first byte of the mask.
4563           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4564           MaskElement = MaskElement.lshr(8);
4565         }
4566       }
4567       DecodePSHUFBMask(RawMask, Mask);
4568       break;
4569     }
4570
4571     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4572     if (!MaskLoad)
4573       return false;
4574
4575     SDValue Ptr = MaskLoad->getBasePtr();
4576     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4577         Ptr->getOpcode() == X86ISD::WrapperRIP)
4578       Ptr = Ptr->getOperand(0);
4579
4580     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4581     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4582       return false;
4583
4584     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4585       DecodePSHUFBMask(C, Mask);
4586       if (Mask.empty())
4587         return false;
4588       break;
4589     }
4590
4591     return false;
4592   }
4593   case X86ISD::VPERMI:
4594     ImmN = N->getOperand(N->getNumOperands()-1);
4595     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4596     IsUnary = true;
4597     break;
4598   case X86ISD::MOVSS:
4599   case X86ISD::MOVSD:
4600     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4601     break;
4602   case X86ISD::VPERM2X128:
4603     ImmN = N->getOperand(N->getNumOperands()-1);
4604     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4605     if (Mask.empty()) return false;
4606     // Mask only contains negative index if an element is zero.
4607     if (std::any_of(Mask.begin(), Mask.end(),
4608                     [](int M){ return M == SM_SentinelZero; }))
4609       return false;
4610     break;
4611   case X86ISD::MOVSLDUP:
4612     DecodeMOVSLDUPMask(VT, Mask);
4613     IsUnary = true;
4614     break;
4615   case X86ISD::MOVSHDUP:
4616     DecodeMOVSHDUPMask(VT, Mask);
4617     IsUnary = true;
4618     break;
4619   case X86ISD::MOVDDUP:
4620     DecodeMOVDDUPMask(VT, Mask);
4621     IsUnary = true;
4622     break;
4623   case X86ISD::MOVLHPD:
4624   case X86ISD::MOVLPD:
4625   case X86ISD::MOVLPS:
4626     // Not yet implemented
4627     return false;
4628   default: llvm_unreachable("unknown target shuffle node");
4629   }
4630
4631   // If we have a fake unary shuffle, the shuffle mask is spread across two
4632   // inputs that are actually the same node. Re-map the mask to always point
4633   // into the first input.
4634   if (IsFakeUnary)
4635     for (int &M : Mask)
4636       if (M >= (int)Mask.size())
4637         M -= Mask.size();
4638
4639   return true;
4640 }
4641
4642 /// Returns the scalar element that will make up the ith
4643 /// element of the result of the vector shuffle.
4644 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4645                                    unsigned Depth) {
4646   if (Depth == 6)
4647     return SDValue();  // Limit search depth.
4648
4649   SDValue V = SDValue(N, 0);
4650   EVT VT = V.getValueType();
4651   unsigned Opcode = V.getOpcode();
4652
4653   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4654   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4655     int Elt = SV->getMaskElt(Index);
4656
4657     if (Elt < 0)
4658       return DAG.getUNDEF(VT.getVectorElementType());
4659
4660     unsigned NumElems = VT.getVectorNumElements();
4661     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4662                                          : SV->getOperand(1);
4663     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4664   }
4665
4666   // Recurse into target specific vector shuffles to find scalars.
4667   if (isTargetShuffle(Opcode)) {
4668     MVT ShufVT = V.getSimpleValueType();
4669     unsigned NumElems = ShufVT.getVectorNumElements();
4670     SmallVector<int, 16> ShuffleMask;
4671     bool IsUnary;
4672
4673     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4674       return SDValue();
4675
4676     int Elt = ShuffleMask[Index];
4677     if (Elt < 0)
4678       return DAG.getUNDEF(ShufVT.getVectorElementType());
4679
4680     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4681                                          : N->getOperand(1);
4682     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4683                                Depth+1);
4684   }
4685
4686   // Actual nodes that may contain scalar elements
4687   if (Opcode == ISD::BITCAST) {
4688     V = V.getOperand(0);
4689     EVT SrcVT = V.getValueType();
4690     unsigned NumElems = VT.getVectorNumElements();
4691
4692     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4693       return SDValue();
4694   }
4695
4696   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4697     return (Index == 0) ? V.getOperand(0)
4698                         : DAG.getUNDEF(VT.getVectorElementType());
4699
4700   if (V.getOpcode() == ISD::BUILD_VECTOR)
4701     return V.getOperand(Index);
4702
4703   return SDValue();
4704 }
4705
4706 /// Custom lower build_vector of v16i8.
4707 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4708                                        unsigned NumNonZero, unsigned NumZero,
4709                                        SelectionDAG &DAG,
4710                                        const X86Subtarget* Subtarget,
4711                                        const TargetLowering &TLI) {
4712   if (NumNonZero > 8)
4713     return SDValue();
4714
4715   SDLoc dl(Op);
4716   SDValue V;
4717   bool First = true;
4718
4719   // SSE4.1 - use PINSRB to insert each byte directly.
4720   if (Subtarget->hasSSE41()) {
4721     for (unsigned i = 0; i < 16; ++i) {
4722       bool isNonZero = (NonZeros & (1 << i)) != 0;
4723       if (isNonZero) {
4724         if (First) {
4725           if (NumZero)
4726             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4727           else
4728             V = DAG.getUNDEF(MVT::v16i8);
4729           First = false;
4730         }
4731         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4732                         MVT::v16i8, V, Op.getOperand(i),
4733                         DAG.getIntPtrConstant(i, dl));
4734       }
4735     }
4736
4737     return V;
4738   }
4739
4740   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4741   for (unsigned i = 0; i < 16; ++i) {
4742     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4743     if (ThisIsNonZero && First) {
4744       if (NumZero)
4745         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4746       else
4747         V = DAG.getUNDEF(MVT::v8i16);
4748       First = false;
4749     }
4750
4751     if ((i & 1) != 0) {
4752       SDValue ThisElt, LastElt;
4753       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4754       if (LastIsNonZero) {
4755         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4756                               MVT::i16, Op.getOperand(i-1));
4757       }
4758       if (ThisIsNonZero) {
4759         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4760         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4761                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4762         if (LastIsNonZero)
4763           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4764       } else
4765         ThisElt = LastElt;
4766
4767       if (ThisElt.getNode())
4768         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4769                         DAG.getIntPtrConstant(i/2, dl));
4770     }
4771   }
4772
4773   return DAG.getBitcast(MVT::v16i8, V);
4774 }
4775
4776 /// Custom lower build_vector of v8i16.
4777 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4778                                      unsigned NumNonZero, unsigned NumZero,
4779                                      SelectionDAG &DAG,
4780                                      const X86Subtarget* Subtarget,
4781                                      const TargetLowering &TLI) {
4782   if (NumNonZero > 4)
4783     return SDValue();
4784
4785   SDLoc dl(Op);
4786   SDValue V;
4787   bool First = true;
4788   for (unsigned i = 0; i < 8; ++i) {
4789     bool isNonZero = (NonZeros & (1 << i)) != 0;
4790     if (isNonZero) {
4791       if (First) {
4792         if (NumZero)
4793           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4794         else
4795           V = DAG.getUNDEF(MVT::v8i16);
4796         First = false;
4797       }
4798       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4799                       MVT::v8i16, V, Op.getOperand(i),
4800                       DAG.getIntPtrConstant(i, dl));
4801     }
4802   }
4803
4804   return V;
4805 }
4806
4807 /// Custom lower build_vector of v4i32 or v4f32.
4808 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4809                                      const X86Subtarget *Subtarget,
4810                                      const TargetLowering &TLI) {
4811   // Find all zeroable elements.
4812   std::bitset<4> Zeroable;
4813   for (int i=0; i < 4; ++i) {
4814     SDValue Elt = Op->getOperand(i);
4815     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4816   }
4817   assert(Zeroable.size() - Zeroable.count() > 1 &&
4818          "We expect at least two non-zero elements!");
4819
4820   // We only know how to deal with build_vector nodes where elements are either
4821   // zeroable or extract_vector_elt with constant index.
4822   SDValue FirstNonZero;
4823   unsigned FirstNonZeroIdx;
4824   for (unsigned i=0; i < 4; ++i) {
4825     if (Zeroable[i])
4826       continue;
4827     SDValue Elt = Op->getOperand(i);
4828     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4829         !isa<ConstantSDNode>(Elt.getOperand(1)))
4830       return SDValue();
4831     // Make sure that this node is extracting from a 128-bit vector.
4832     MVT VT = Elt.getOperand(0).getSimpleValueType();
4833     if (!VT.is128BitVector())
4834       return SDValue();
4835     if (!FirstNonZero.getNode()) {
4836       FirstNonZero = Elt;
4837       FirstNonZeroIdx = i;
4838     }
4839   }
4840
4841   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4842   SDValue V1 = FirstNonZero.getOperand(0);
4843   MVT VT = V1.getSimpleValueType();
4844
4845   // See if this build_vector can be lowered as a blend with zero.
4846   SDValue Elt;
4847   unsigned EltMaskIdx, EltIdx;
4848   int Mask[4];
4849   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4850     if (Zeroable[EltIdx]) {
4851       // The zero vector will be on the right hand side.
4852       Mask[EltIdx] = EltIdx+4;
4853       continue;
4854     }
4855
4856     Elt = Op->getOperand(EltIdx);
4857     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4858     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4859     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4860       break;
4861     Mask[EltIdx] = EltIdx;
4862   }
4863
4864   if (EltIdx == 4) {
4865     // Let the shuffle legalizer deal with blend operations.
4866     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4867     if (V1.getSimpleValueType() != VT)
4868       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4869     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4870   }
4871
4872   // See if we can lower this build_vector to a INSERTPS.
4873   if (!Subtarget->hasSSE41())
4874     return SDValue();
4875
4876   SDValue V2 = Elt.getOperand(0);
4877   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4878     V1 = SDValue();
4879
4880   bool CanFold = true;
4881   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4882     if (Zeroable[i])
4883       continue;
4884
4885     SDValue Current = Op->getOperand(i);
4886     SDValue SrcVector = Current->getOperand(0);
4887     if (!V1.getNode())
4888       V1 = SrcVector;
4889     CanFold = SrcVector == V1 &&
4890       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4891   }
4892
4893   if (!CanFold)
4894     return SDValue();
4895
4896   assert(V1.getNode() && "Expected at least two non-zero elements!");
4897   if (V1.getSimpleValueType() != MVT::v4f32)
4898     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4899   if (V2.getSimpleValueType() != MVT::v4f32)
4900     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4901
4902   // Ok, we can emit an INSERTPS instruction.
4903   unsigned ZMask = Zeroable.to_ulong();
4904
4905   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4906   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4907   SDLoc DL(Op);
4908   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4909                                DAG.getIntPtrConstant(InsertPSMask, DL));
4910   return DAG.getBitcast(VT, Result);
4911 }
4912
4913 /// Return a vector logical shift node.
4914 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4915                          unsigned NumBits, SelectionDAG &DAG,
4916                          const TargetLowering &TLI, SDLoc dl) {
4917   assert(VT.is128BitVector() && "Unknown type for VShift");
4918   MVT ShVT = MVT::v2i64;
4919   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4920   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4921   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4922   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4923   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4924   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4925 }
4926
4927 static SDValue
4928 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4929
4930   // Check if the scalar load can be widened into a vector load. And if
4931   // the address is "base + cst" see if the cst can be "absorbed" into
4932   // the shuffle mask.
4933   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4934     SDValue Ptr = LD->getBasePtr();
4935     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4936       return SDValue();
4937     EVT PVT = LD->getValueType(0);
4938     if (PVT != MVT::i32 && PVT != MVT::f32)
4939       return SDValue();
4940
4941     int FI = -1;
4942     int64_t Offset = 0;
4943     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4944       FI = FINode->getIndex();
4945       Offset = 0;
4946     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4947                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4948       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4949       Offset = Ptr.getConstantOperandVal(1);
4950       Ptr = Ptr.getOperand(0);
4951     } else {
4952       return SDValue();
4953     }
4954
4955     // FIXME: 256-bit vector instructions don't require a strict alignment,
4956     // improve this code to support it better.
4957     unsigned RequiredAlign = VT.getSizeInBits()/8;
4958     SDValue Chain = LD->getChain();
4959     // Make sure the stack object alignment is at least 16 or 32.
4960     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4961     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4962       if (MFI->isFixedObjectIndex(FI)) {
4963         // Can't change the alignment. FIXME: It's possible to compute
4964         // the exact stack offset and reference FI + adjust offset instead.
4965         // If someone *really* cares about this. That's the way to implement it.
4966         return SDValue();
4967       } else {
4968         MFI->setObjectAlignment(FI, RequiredAlign);
4969       }
4970     }
4971
4972     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4973     // Ptr + (Offset & ~15).
4974     if (Offset < 0)
4975       return SDValue();
4976     if ((Offset % RequiredAlign) & 3)
4977       return SDValue();
4978     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4979     if (StartOffset) {
4980       SDLoc DL(Ptr);
4981       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4982                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4983     }
4984
4985     int EltNo = (Offset - StartOffset) >> 2;
4986     unsigned NumElems = VT.getVectorNumElements();
4987
4988     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4989     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4990                              LD->getPointerInfo().getWithOffset(StartOffset),
4991                              false, false, false, 0);
4992
4993     SmallVector<int, 8> Mask(NumElems, EltNo);
4994
4995     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4996   }
4997
4998   return SDValue();
4999 }
5000
5001 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5002 /// elements can be replaced by a single large load which has the same value as
5003 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5004 ///
5005 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5006 ///
5007 /// FIXME: we'd also like to handle the case where the last elements are zero
5008 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5009 /// There's even a handy isZeroNode for that purpose.
5010 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5011                                         SDLoc &DL, SelectionDAG &DAG,
5012                                         bool isAfterLegalize) {
5013   unsigned NumElems = Elts.size();
5014
5015   LoadSDNode *LDBase = nullptr;
5016   unsigned LastLoadedElt = -1U;
5017
5018   // For each element in the initializer, see if we've found a load or an undef.
5019   // If we don't find an initial load element, or later load elements are
5020   // non-consecutive, bail out.
5021   for (unsigned i = 0; i < NumElems; ++i) {
5022     SDValue Elt = Elts[i];
5023     // Look through a bitcast.
5024     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5025       Elt = Elt.getOperand(0);
5026     if (!Elt.getNode() ||
5027         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5028       return SDValue();
5029     if (!LDBase) {
5030       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5031         return SDValue();
5032       LDBase = cast<LoadSDNode>(Elt.getNode());
5033       LastLoadedElt = i;
5034       continue;
5035     }
5036     if (Elt.getOpcode() == ISD::UNDEF)
5037       continue;
5038
5039     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5040     EVT LdVT = Elt.getValueType();
5041     // Each loaded element must be the correct fractional portion of the
5042     // requested vector load.
5043     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5044       return SDValue();
5045     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5046       return SDValue();
5047     LastLoadedElt = i;
5048   }
5049
5050   // If we have found an entire vector of loads and undefs, then return a large
5051   // load of the entire vector width starting at the base pointer.  If we found
5052   // consecutive loads for the low half, generate a vzext_load node.
5053   if (LastLoadedElt == NumElems - 1) {
5054     assert(LDBase && "Did not find base load for merging consecutive loads");
5055     EVT EltVT = LDBase->getValueType(0);
5056     // Ensure that the input vector size for the merged loads matches the
5057     // cumulative size of the input elements.
5058     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5059       return SDValue();
5060
5061     if (isAfterLegalize &&
5062         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5063       return SDValue();
5064
5065     SDValue NewLd = SDValue();
5066
5067     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5068                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5069                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5070                         LDBase->getAlignment());
5071
5072     if (LDBase->hasAnyUseOfValue(1)) {
5073       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5074                                      SDValue(LDBase, 1),
5075                                      SDValue(NewLd.getNode(), 1));
5076       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5077       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5078                              SDValue(NewLd.getNode(), 1));
5079     }
5080
5081     return NewLd;
5082   }
5083
5084   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5085   //of a v4i32 / v4f32. It's probably worth generalizing.
5086   EVT EltVT = VT.getVectorElementType();
5087   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5088       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5089     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5090     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5091     SDValue ResNode =
5092         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5093                                 LDBase->getPointerInfo(),
5094                                 LDBase->getAlignment(),
5095                                 false/*isVolatile*/, true/*ReadMem*/,
5096                                 false/*WriteMem*/);
5097
5098     // Make sure the newly-created LOAD is in the same position as LDBase in
5099     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5100     // update uses of LDBase's output chain to use the TokenFactor.
5101     if (LDBase->hasAnyUseOfValue(1)) {
5102       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5103                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5104       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5105       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5106                              SDValue(ResNode.getNode(), 1));
5107     }
5108
5109     return DAG.getBitcast(VT, ResNode);
5110   }
5111   return SDValue();
5112 }
5113
5114 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5115 /// to generate a splat value for the following cases:
5116 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5117 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5118 /// a scalar load, or a constant.
5119 /// The VBROADCAST node is returned when a pattern is found,
5120 /// or SDValue() otherwise.
5121 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5122                                     SelectionDAG &DAG) {
5123   // VBROADCAST requires AVX.
5124   // TODO: Splats could be generated for non-AVX CPUs using SSE
5125   // instructions, but there's less potential gain for only 128-bit vectors.
5126   if (!Subtarget->hasAVX())
5127     return SDValue();
5128
5129   MVT VT = Op.getSimpleValueType();
5130   SDLoc dl(Op);
5131
5132   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5133          "Unsupported vector type for broadcast.");
5134
5135   SDValue Ld;
5136   bool ConstSplatVal;
5137
5138   switch (Op.getOpcode()) {
5139     default:
5140       // Unknown pattern found.
5141       return SDValue();
5142
5143     case ISD::BUILD_VECTOR: {
5144       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5145       BitVector UndefElements;
5146       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5147
5148       // We need a splat of a single value to use broadcast, and it doesn't
5149       // make any sense if the value is only in one element of the vector.
5150       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5151         return SDValue();
5152
5153       Ld = Splat;
5154       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5155                        Ld.getOpcode() == ISD::ConstantFP);
5156
5157       // Make sure that all of the users of a non-constant load are from the
5158       // BUILD_VECTOR node.
5159       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5160         return SDValue();
5161       break;
5162     }
5163
5164     case ISD::VECTOR_SHUFFLE: {
5165       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5166
5167       // Shuffles must have a splat mask where the first element is
5168       // broadcasted.
5169       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5170         return SDValue();
5171
5172       SDValue Sc = Op.getOperand(0);
5173       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5174           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5175
5176         if (!Subtarget->hasInt256())
5177           return SDValue();
5178
5179         // Use the register form of the broadcast instruction available on AVX2.
5180         if (VT.getSizeInBits() >= 256)
5181           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5182         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5183       }
5184
5185       Ld = Sc.getOperand(0);
5186       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5187                        Ld.getOpcode() == ISD::ConstantFP);
5188
5189       // The scalar_to_vector node and the suspected
5190       // load node must have exactly one user.
5191       // Constants may have multiple users.
5192
5193       // AVX-512 has register version of the broadcast
5194       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5195         Ld.getValueType().getSizeInBits() >= 32;
5196       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5197           !hasRegVer))
5198         return SDValue();
5199       break;
5200     }
5201   }
5202
5203   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5204   bool IsGE256 = (VT.getSizeInBits() >= 256);
5205
5206   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5207   // instruction to save 8 or more bytes of constant pool data.
5208   // TODO: If multiple splats are generated to load the same constant,
5209   // it may be detrimental to overall size. There needs to be a way to detect
5210   // that condition to know if this is truly a size win.
5211   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5212
5213   // Handle broadcasting a single constant scalar from the constant pool
5214   // into a vector.
5215   // On Sandybridge (no AVX2), it is still better to load a constant vector
5216   // from the constant pool and not to broadcast it from a scalar.
5217   // But override that restriction when optimizing for size.
5218   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5219   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5220     EVT CVT = Ld.getValueType();
5221     assert(!CVT.isVector() && "Must not broadcast a vector type");
5222
5223     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5224     // For size optimization, also splat v2f64 and v2i64, and for size opt
5225     // with AVX2, also splat i8 and i16.
5226     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5227     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5228         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5229       const Constant *C = nullptr;
5230       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5231         C = CI->getConstantIntValue();
5232       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5233         C = CF->getConstantFPValue();
5234
5235       assert(C && "Invalid constant type");
5236
5237       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5238       SDValue CP =
5239           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5240       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5241       Ld = DAG.getLoad(
5242           CVT, dl, DAG.getEntryNode(), CP,
5243           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5244           false, false, Alignment);
5245
5246       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5247     }
5248   }
5249
5250   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5251
5252   // Handle AVX2 in-register broadcasts.
5253   if (!IsLoad && Subtarget->hasInt256() &&
5254       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5255     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5256
5257   // The scalar source must be a normal load.
5258   if (!IsLoad)
5259     return SDValue();
5260
5261   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5262       (Subtarget->hasVLX() && ScalarSize == 64))
5263     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5264
5265   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5266   // double since there is no vbroadcastsd xmm
5267   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5268     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5269       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5270   }
5271
5272   // Unsupported broadcast.
5273   return SDValue();
5274 }
5275
5276 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5277 /// underlying vector and index.
5278 ///
5279 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5280 /// index.
5281 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5282                                          SDValue ExtIdx) {
5283   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5284   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5285     return Idx;
5286
5287   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5288   // lowered this:
5289   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5290   // to:
5291   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5292   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5293   //                           undef)
5294   //                       Constant<0>)
5295   // In this case the vector is the extract_subvector expression and the index
5296   // is 2, as specified by the shuffle.
5297   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5298   SDValue ShuffleVec = SVOp->getOperand(0);
5299   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5300   assert(ShuffleVecVT.getVectorElementType() ==
5301          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5302
5303   int ShuffleIdx = SVOp->getMaskElt(Idx);
5304   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5305     ExtractedFromVec = ShuffleVec;
5306     return ShuffleIdx;
5307   }
5308   return Idx;
5309 }
5310
5311 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5312   MVT VT = Op.getSimpleValueType();
5313
5314   // Skip if insert_vec_elt is not supported.
5315   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5316   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5317     return SDValue();
5318
5319   SDLoc DL(Op);
5320   unsigned NumElems = Op.getNumOperands();
5321
5322   SDValue VecIn1;
5323   SDValue VecIn2;
5324   SmallVector<unsigned, 4> InsertIndices;
5325   SmallVector<int, 8> Mask(NumElems, -1);
5326
5327   for (unsigned i = 0; i != NumElems; ++i) {
5328     unsigned Opc = Op.getOperand(i).getOpcode();
5329
5330     if (Opc == ISD::UNDEF)
5331       continue;
5332
5333     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5334       // Quit if more than 1 elements need inserting.
5335       if (InsertIndices.size() > 1)
5336         return SDValue();
5337
5338       InsertIndices.push_back(i);
5339       continue;
5340     }
5341
5342     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5343     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5344     // Quit if non-constant index.
5345     if (!isa<ConstantSDNode>(ExtIdx))
5346       return SDValue();
5347     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5348
5349     // Quit if extracted from vector of different type.
5350     if (ExtractedFromVec.getValueType() != VT)
5351       return SDValue();
5352
5353     if (!VecIn1.getNode())
5354       VecIn1 = ExtractedFromVec;
5355     else if (VecIn1 != ExtractedFromVec) {
5356       if (!VecIn2.getNode())
5357         VecIn2 = ExtractedFromVec;
5358       else if (VecIn2 != ExtractedFromVec)
5359         // Quit if more than 2 vectors to shuffle
5360         return SDValue();
5361     }
5362
5363     if (ExtractedFromVec == VecIn1)
5364       Mask[i] = Idx;
5365     else if (ExtractedFromVec == VecIn2)
5366       Mask[i] = Idx + NumElems;
5367   }
5368
5369   if (!VecIn1.getNode())
5370     return SDValue();
5371
5372   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5373   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5374   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5375     unsigned Idx = InsertIndices[i];
5376     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5377                      DAG.getIntPtrConstant(Idx, DL));
5378   }
5379
5380   return NV;
5381 }
5382
5383 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5384   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5385          Op.getScalarValueSizeInBits() == 1 &&
5386          "Can not convert non-constant vector");
5387   uint64_t Immediate = 0;
5388   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5389     SDValue In = Op.getOperand(idx);
5390     if (In.getOpcode() != ISD::UNDEF)
5391       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5392   }
5393   SDLoc dl(Op);
5394   MVT VT =
5395    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5396   return DAG.getConstant(Immediate, dl, VT);
5397 }
5398 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5399 SDValue
5400 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5401
5402   MVT VT = Op.getSimpleValueType();
5403   assert((VT.getVectorElementType() == MVT::i1) &&
5404          "Unexpected type in LowerBUILD_VECTORvXi1!");
5405
5406   SDLoc dl(Op);
5407   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5408     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5409     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5410     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5411   }
5412
5413   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5414     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5415     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5416     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5417   }
5418
5419   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5420     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5421     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5422       return DAG.getBitcast(VT, Imm);
5423     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5424     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5425                         DAG.getIntPtrConstant(0, dl));
5426   }
5427
5428   // Vector has one or more non-const elements
5429   uint64_t Immediate = 0;
5430   SmallVector<unsigned, 16> NonConstIdx;
5431   bool IsSplat = true;
5432   bool HasConstElts = false;
5433   int SplatIdx = -1;
5434   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5435     SDValue In = Op.getOperand(idx);
5436     if (In.getOpcode() == ISD::UNDEF)
5437       continue;
5438     if (!isa<ConstantSDNode>(In))
5439       NonConstIdx.push_back(idx);
5440     else {
5441       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5442       HasConstElts = true;
5443     }
5444     if (SplatIdx == -1)
5445       SplatIdx = idx;
5446     else if (In != Op.getOperand(SplatIdx))
5447       IsSplat = false;
5448   }
5449
5450   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5451   if (IsSplat)
5452     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5453                        DAG.getConstant(1, dl, VT),
5454                        DAG.getConstant(0, dl, VT));
5455
5456   // insert elements one by one
5457   SDValue DstVec;
5458   SDValue Imm;
5459   if (Immediate) {
5460     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5461     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5462   }
5463   else if (HasConstElts)
5464     Imm = DAG.getConstant(0, dl, VT);
5465   else
5466     Imm = DAG.getUNDEF(VT);
5467   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5468     DstVec = DAG.getBitcast(VT, Imm);
5469   else {
5470     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5471     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5472                          DAG.getIntPtrConstant(0, dl));
5473   }
5474
5475   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5476     unsigned InsertIdx = NonConstIdx[i];
5477     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5478                          Op.getOperand(InsertIdx),
5479                          DAG.getIntPtrConstant(InsertIdx, dl));
5480   }
5481   return DstVec;
5482 }
5483
5484 /// \brief Return true if \p N implements a horizontal binop and return the
5485 /// operands for the horizontal binop into V0 and V1.
5486 ///
5487 /// This is a helper function of LowerToHorizontalOp().
5488 /// This function checks that the build_vector \p N in input implements a
5489 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5490 /// operation to match.
5491 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5492 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5493 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5494 /// arithmetic sub.
5495 ///
5496 /// This function only analyzes elements of \p N whose indices are
5497 /// in range [BaseIdx, LastIdx).
5498 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5499                               SelectionDAG &DAG,
5500                               unsigned BaseIdx, unsigned LastIdx,
5501                               SDValue &V0, SDValue &V1) {
5502   EVT VT = N->getValueType(0);
5503
5504   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5505   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5506          "Invalid Vector in input!");
5507
5508   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5509   bool CanFold = true;
5510   unsigned ExpectedVExtractIdx = BaseIdx;
5511   unsigned NumElts = LastIdx - BaseIdx;
5512   V0 = DAG.getUNDEF(VT);
5513   V1 = DAG.getUNDEF(VT);
5514
5515   // Check if N implements a horizontal binop.
5516   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5517     SDValue Op = N->getOperand(i + BaseIdx);
5518
5519     // Skip UNDEFs.
5520     if (Op->getOpcode() == ISD::UNDEF) {
5521       // Update the expected vector extract index.
5522       if (i * 2 == NumElts)
5523         ExpectedVExtractIdx = BaseIdx;
5524       ExpectedVExtractIdx += 2;
5525       continue;
5526     }
5527
5528     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5529
5530     if (!CanFold)
5531       break;
5532
5533     SDValue Op0 = Op.getOperand(0);
5534     SDValue Op1 = Op.getOperand(1);
5535
5536     // Try to match the following pattern:
5537     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5538     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5539         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5540         Op0.getOperand(0) == Op1.getOperand(0) &&
5541         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5542         isa<ConstantSDNode>(Op1.getOperand(1)));
5543     if (!CanFold)
5544       break;
5545
5546     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5547     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5548
5549     if (i * 2 < NumElts) {
5550       if (V0.getOpcode() == ISD::UNDEF) {
5551         V0 = Op0.getOperand(0);
5552         if (V0.getValueType() != VT)
5553           return false;
5554       }
5555     } else {
5556       if (V1.getOpcode() == ISD::UNDEF) {
5557         V1 = Op0.getOperand(0);
5558         if (V1.getValueType() != VT)
5559           return false;
5560       }
5561       if (i * 2 == NumElts)
5562         ExpectedVExtractIdx = BaseIdx;
5563     }
5564
5565     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5566     if (I0 == ExpectedVExtractIdx)
5567       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5568     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5569       // Try to match the following dag sequence:
5570       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5571       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5572     } else
5573       CanFold = false;
5574
5575     ExpectedVExtractIdx += 2;
5576   }
5577
5578   return CanFold;
5579 }
5580
5581 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5582 /// a concat_vector.
5583 ///
5584 /// This is a helper function of LowerToHorizontalOp().
5585 /// This function expects two 256-bit vectors called V0 and V1.
5586 /// At first, each vector is split into two separate 128-bit vectors.
5587 /// Then, the resulting 128-bit vectors are used to implement two
5588 /// horizontal binary operations.
5589 ///
5590 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5591 ///
5592 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5593 /// the two new horizontal binop.
5594 /// When Mode is set, the first horizontal binop dag node would take as input
5595 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5596 /// horizontal binop dag node would take as input the lower 128-bit of V1
5597 /// and the upper 128-bit of V1.
5598 ///   Example:
5599 ///     HADD V0_LO, V0_HI
5600 ///     HADD V1_LO, V1_HI
5601 ///
5602 /// Otherwise, the first horizontal binop dag node takes as input the lower
5603 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5604 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5605 ///   Example:
5606 ///     HADD V0_LO, V1_LO
5607 ///     HADD V0_HI, V1_HI
5608 ///
5609 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5610 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5611 /// the upper 128-bits of the result.
5612 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5613                                      SDLoc DL, SelectionDAG &DAG,
5614                                      unsigned X86Opcode, bool Mode,
5615                                      bool isUndefLO, bool isUndefHI) {
5616   EVT VT = V0.getValueType();
5617   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5618          "Invalid nodes in input!");
5619
5620   unsigned NumElts = VT.getVectorNumElements();
5621   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5622   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5623   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5624   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5625   EVT NewVT = V0_LO.getValueType();
5626
5627   SDValue LO = DAG.getUNDEF(NewVT);
5628   SDValue HI = DAG.getUNDEF(NewVT);
5629
5630   if (Mode) {
5631     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5632     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5633       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5634     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5635       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5636   } else {
5637     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5638     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5639                        V1_LO->getOpcode() != ISD::UNDEF))
5640       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5641
5642     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5643                        V1_HI->getOpcode() != ISD::UNDEF))
5644       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5645   }
5646
5647   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5648 }
5649
5650 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5651 /// node.
5652 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5653                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5654   EVT VT = BV->getValueType(0);
5655   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5656       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5657     return SDValue();
5658
5659   SDLoc DL(BV);
5660   unsigned NumElts = VT.getVectorNumElements();
5661   SDValue InVec0 = DAG.getUNDEF(VT);
5662   SDValue InVec1 = DAG.getUNDEF(VT);
5663
5664   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5665           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5666
5667   // Odd-numbered elements in the input build vector are obtained from
5668   // adding two integer/float elements.
5669   // Even-numbered elements in the input build vector are obtained from
5670   // subtracting two integer/float elements.
5671   unsigned ExpectedOpcode = ISD::FSUB;
5672   unsigned NextExpectedOpcode = ISD::FADD;
5673   bool AddFound = false;
5674   bool SubFound = false;
5675
5676   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5677     SDValue Op = BV->getOperand(i);
5678
5679     // Skip 'undef' values.
5680     unsigned Opcode = Op.getOpcode();
5681     if (Opcode == ISD::UNDEF) {
5682       std::swap(ExpectedOpcode, NextExpectedOpcode);
5683       continue;
5684     }
5685
5686     // Early exit if we found an unexpected opcode.
5687     if (Opcode != ExpectedOpcode)
5688       return SDValue();
5689
5690     SDValue Op0 = Op.getOperand(0);
5691     SDValue Op1 = Op.getOperand(1);
5692
5693     // Try to match the following pattern:
5694     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5695     // Early exit if we cannot match that sequence.
5696     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5697         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5698         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5699         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5700         Op0.getOperand(1) != Op1.getOperand(1))
5701       return SDValue();
5702
5703     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5704     if (I0 != i)
5705       return SDValue();
5706
5707     // We found a valid add/sub node. Update the information accordingly.
5708     if (i & 1)
5709       AddFound = true;
5710     else
5711       SubFound = true;
5712
5713     // Update InVec0 and InVec1.
5714     if (InVec0.getOpcode() == ISD::UNDEF) {
5715       InVec0 = Op0.getOperand(0);
5716       if (InVec0.getValueType() != VT)
5717         return SDValue();
5718     }
5719     if (InVec1.getOpcode() == ISD::UNDEF) {
5720       InVec1 = Op1.getOperand(0);
5721       if (InVec1.getValueType() != VT)
5722         return SDValue();
5723     }
5724
5725     // Make sure that operands in input to each add/sub node always
5726     // come from a same pair of vectors.
5727     if (InVec0 != Op0.getOperand(0)) {
5728       if (ExpectedOpcode == ISD::FSUB)
5729         return SDValue();
5730
5731       // FADD is commutable. Try to commute the operands
5732       // and then test again.
5733       std::swap(Op0, Op1);
5734       if (InVec0 != Op0.getOperand(0))
5735         return SDValue();
5736     }
5737
5738     if (InVec1 != Op1.getOperand(0))
5739       return SDValue();
5740
5741     // Update the pair of expected opcodes.
5742     std::swap(ExpectedOpcode, NextExpectedOpcode);
5743   }
5744
5745   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5746   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5747       InVec1.getOpcode() != ISD::UNDEF)
5748     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5749
5750   return SDValue();
5751 }
5752
5753 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5754 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5755                                    const X86Subtarget *Subtarget,
5756                                    SelectionDAG &DAG) {
5757   EVT VT = BV->getValueType(0);
5758   unsigned NumElts = VT.getVectorNumElements();
5759   unsigned NumUndefsLO = 0;
5760   unsigned NumUndefsHI = 0;
5761   unsigned Half = NumElts/2;
5762
5763   // Count the number of UNDEF operands in the build_vector in input.
5764   for (unsigned i = 0, e = Half; i != e; ++i)
5765     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5766       NumUndefsLO++;
5767
5768   for (unsigned i = Half, e = NumElts; i != e; ++i)
5769     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5770       NumUndefsHI++;
5771
5772   // Early exit if this is either a build_vector of all UNDEFs or all the
5773   // operands but one are UNDEF.
5774   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5775     return SDValue();
5776
5777   SDLoc DL(BV);
5778   SDValue InVec0, InVec1;
5779   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5780     // Try to match an SSE3 float HADD/HSUB.
5781     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5782       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5783
5784     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5785       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5786   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5787     // Try to match an SSSE3 integer HADD/HSUB.
5788     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5789       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5790
5791     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5792       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5793   }
5794
5795   if (!Subtarget->hasAVX())
5796     return SDValue();
5797
5798   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5799     // Try to match an AVX horizontal add/sub of packed single/double
5800     // precision floating point values from 256-bit vectors.
5801     SDValue InVec2, InVec3;
5802     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5803         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5804         ((InVec0.getOpcode() == ISD::UNDEF ||
5805           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5806         ((InVec1.getOpcode() == ISD::UNDEF ||
5807           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5808       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5809
5810     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5811         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5812         ((InVec0.getOpcode() == ISD::UNDEF ||
5813           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5814         ((InVec1.getOpcode() == ISD::UNDEF ||
5815           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5816       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5817   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5818     // Try to match an AVX2 horizontal add/sub of signed integers.
5819     SDValue InVec2, InVec3;
5820     unsigned X86Opcode;
5821     bool CanFold = true;
5822
5823     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5824         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5825         ((InVec0.getOpcode() == ISD::UNDEF ||
5826           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5827         ((InVec1.getOpcode() == ISD::UNDEF ||
5828           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5829       X86Opcode = X86ISD::HADD;
5830     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5831         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5832         ((InVec0.getOpcode() == ISD::UNDEF ||
5833           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5834         ((InVec1.getOpcode() == ISD::UNDEF ||
5835           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5836       X86Opcode = X86ISD::HSUB;
5837     else
5838       CanFold = false;
5839
5840     if (CanFold) {
5841       // Fold this build_vector into a single horizontal add/sub.
5842       // Do this only if the target has AVX2.
5843       if (Subtarget->hasAVX2())
5844         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5845
5846       // Do not try to expand this build_vector into a pair of horizontal
5847       // add/sub if we can emit a pair of scalar add/sub.
5848       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5849         return SDValue();
5850
5851       // Convert this build_vector into a pair of horizontal binop followed by
5852       // a concat vector.
5853       bool isUndefLO = NumUndefsLO == Half;
5854       bool isUndefHI = NumUndefsHI == Half;
5855       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5856                                    isUndefLO, isUndefHI);
5857     }
5858   }
5859
5860   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5861        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5862     unsigned X86Opcode;
5863     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5864       X86Opcode = X86ISD::HADD;
5865     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5866       X86Opcode = X86ISD::HSUB;
5867     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5868       X86Opcode = X86ISD::FHADD;
5869     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5870       X86Opcode = X86ISD::FHSUB;
5871     else
5872       return SDValue();
5873
5874     // Don't try to expand this build_vector into a pair of horizontal add/sub
5875     // if we can simply emit a pair of scalar add/sub.
5876     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5877       return SDValue();
5878
5879     // Convert this build_vector into two horizontal add/sub followed by
5880     // a concat vector.
5881     bool isUndefLO = NumUndefsLO == Half;
5882     bool isUndefHI = NumUndefsHI == Half;
5883     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5884                                  isUndefLO, isUndefHI);
5885   }
5886
5887   return SDValue();
5888 }
5889
5890 SDValue
5891 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5892   SDLoc dl(Op);
5893
5894   MVT VT = Op.getSimpleValueType();
5895   MVT ExtVT = VT.getVectorElementType();
5896   unsigned NumElems = Op.getNumOperands();
5897
5898   // Generate vectors for predicate vectors.
5899   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5900     return LowerBUILD_VECTORvXi1(Op, DAG);
5901
5902   // Vectors containing all zeros can be matched by pxor and xorps later
5903   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5904     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5905     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5906     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5907       return Op;
5908
5909     return getZeroVector(VT, Subtarget, DAG, dl);
5910   }
5911
5912   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5913   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5914   // vpcmpeqd on 256-bit vectors.
5915   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5916     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5917       return Op;
5918
5919     if (!VT.is512BitVector())
5920       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5921   }
5922
5923   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5924   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5925     return AddSub;
5926   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5927     return HorizontalOp;
5928   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5929     return Broadcast;
5930
5931   unsigned EVTBits = ExtVT.getSizeInBits();
5932
5933   unsigned NumZero  = 0;
5934   unsigned NumNonZero = 0;
5935   unsigned NonZeros = 0;
5936   bool IsAllConstants = true;
5937   SmallSet<SDValue, 8> Values;
5938   for (unsigned i = 0; i < NumElems; ++i) {
5939     SDValue Elt = Op.getOperand(i);
5940     if (Elt.getOpcode() == ISD::UNDEF)
5941       continue;
5942     Values.insert(Elt);
5943     if (Elt.getOpcode() != ISD::Constant &&
5944         Elt.getOpcode() != ISD::ConstantFP)
5945       IsAllConstants = false;
5946     if (X86::isZeroNode(Elt))
5947       NumZero++;
5948     else {
5949       NonZeros |= (1 << i);
5950       NumNonZero++;
5951     }
5952   }
5953
5954   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5955   if (NumNonZero == 0)
5956     return DAG.getUNDEF(VT);
5957
5958   // Special case for single non-zero, non-undef, element.
5959   if (NumNonZero == 1) {
5960     unsigned Idx = countTrailingZeros(NonZeros);
5961     SDValue Item = Op.getOperand(Idx);
5962
5963     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5964     // the value are obviously zero, truncate the value to i32 and do the
5965     // insertion that way.  Only do this if the value is non-constant or if the
5966     // value is a constant being inserted into element 0.  It is cheaper to do
5967     // a constant pool load than it is to do a movd + shuffle.
5968     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5969         (!IsAllConstants || Idx == 0)) {
5970       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5971         // Handle SSE only.
5972         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5973         EVT VecVT = MVT::v4i32;
5974
5975         // Truncate the value (which may itself be a constant) to i32, and
5976         // convert it to a vector with movd (S2V+shuffle to zero extend).
5977         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5978         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5979         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5980                                       Item, Idx * 2, true, Subtarget, DAG));
5981       }
5982     }
5983
5984     // If we have a constant or non-constant insertion into the low element of
5985     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5986     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5987     // depending on what the source datatype is.
5988     if (Idx == 0) {
5989       if (NumZero == 0)
5990         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5991
5992       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5993           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5994         if (VT.is512BitVector()) {
5995           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5996           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5997                              Item, DAG.getIntPtrConstant(0, dl));
5998         }
5999         assert((VT.is128BitVector() || VT.is256BitVector()) &&
6000                "Expected an SSE value type!");
6001         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6002         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6003         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6004       }
6005
6006       // We can't directly insert an i8 or i16 into a vector, so zero extend
6007       // it to i32 first.
6008       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6009         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6010         if (VT.is256BitVector()) {
6011           if (Subtarget->hasAVX()) {
6012             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6013             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6014           } else {
6015             // Without AVX, we need to extend to a 128-bit vector and then
6016             // insert into the 256-bit vector.
6017             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6018             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6019             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6020           }
6021         } else {
6022           assert(VT.is128BitVector() && "Expected an SSE value type!");
6023           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6024           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6025         }
6026         return DAG.getBitcast(VT, Item);
6027       }
6028     }
6029
6030     // Is it a vector logical left shift?
6031     if (NumElems == 2 && Idx == 1 &&
6032         X86::isZeroNode(Op.getOperand(0)) &&
6033         !X86::isZeroNode(Op.getOperand(1))) {
6034       unsigned NumBits = VT.getSizeInBits();
6035       return getVShift(true, VT,
6036                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6037                                    VT, Op.getOperand(1)),
6038                        NumBits/2, DAG, *this, dl);
6039     }
6040
6041     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6042       return SDValue();
6043
6044     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6045     // is a non-constant being inserted into an element other than the low one,
6046     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6047     // movd/movss) to move this into the low element, then shuffle it into
6048     // place.
6049     if (EVTBits == 32) {
6050       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6051       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6052     }
6053   }
6054
6055   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6056   if (Values.size() == 1) {
6057     if (EVTBits == 32) {
6058       // Instead of a shuffle like this:
6059       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6060       // Check if it's possible to issue this instead.
6061       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6062       unsigned Idx = countTrailingZeros(NonZeros);
6063       SDValue Item = Op.getOperand(Idx);
6064       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6065         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6066     }
6067     return SDValue();
6068   }
6069
6070   // A vector full of immediates; various special cases are already
6071   // handled, so this is best done with a single constant-pool load.
6072   if (IsAllConstants)
6073     return SDValue();
6074
6075   // For AVX-length vectors, see if we can use a vector load to get all of the
6076   // elements, otherwise build the individual 128-bit pieces and use
6077   // shuffles to put them in place.
6078   if (VT.is256BitVector() || VT.is512BitVector()) {
6079     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6080
6081     // Check for a build vector of consecutive loads.
6082     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6083       return LD;
6084
6085     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6086
6087     // Build both the lower and upper subvector.
6088     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6089                                 makeArrayRef(&V[0], NumElems/2));
6090     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6091                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6092
6093     // Recreate the wider vector with the lower and upper part.
6094     if (VT.is256BitVector())
6095       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6096     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6097   }
6098
6099   // Let legalizer expand 2-wide build_vectors.
6100   if (EVTBits == 64) {
6101     if (NumNonZero == 1) {
6102       // One half is zero or undef.
6103       unsigned Idx = countTrailingZeros(NonZeros);
6104       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6105                                  Op.getOperand(Idx));
6106       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6107     }
6108     return SDValue();
6109   }
6110
6111   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6112   if (EVTBits == 8 && NumElems == 16)
6113     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6114                                         Subtarget, *this))
6115       return V;
6116
6117   if (EVTBits == 16 && NumElems == 8)
6118     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6119                                       Subtarget, *this))
6120       return V;
6121
6122   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6123   if (EVTBits == 32 && NumElems == 4)
6124     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6125       return V;
6126
6127   // If element VT is == 32 bits, turn it into a number of shuffles.
6128   SmallVector<SDValue, 8> V(NumElems);
6129   if (NumElems == 4 && NumZero > 0) {
6130     for (unsigned i = 0; i < 4; ++i) {
6131       bool isZero = !(NonZeros & (1 << i));
6132       if (isZero)
6133         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6134       else
6135         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6136     }
6137
6138     for (unsigned i = 0; i < 2; ++i) {
6139       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6140         default: break;
6141         case 0:
6142           V[i] = V[i*2];  // Must be a zero vector.
6143           break;
6144         case 1:
6145           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6146           break;
6147         case 2:
6148           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6149           break;
6150         case 3:
6151           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6152           break;
6153       }
6154     }
6155
6156     bool Reverse1 = (NonZeros & 0x3) == 2;
6157     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6158     int MaskVec[] = {
6159       Reverse1 ? 1 : 0,
6160       Reverse1 ? 0 : 1,
6161       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6162       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6163     };
6164     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6165   }
6166
6167   if (Values.size() > 1 && VT.is128BitVector()) {
6168     // Check for a build vector of consecutive loads.
6169     for (unsigned i = 0; i < NumElems; ++i)
6170       V[i] = Op.getOperand(i);
6171
6172     // Check for elements which are consecutive loads.
6173     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6174       return LD;
6175
6176     // Check for a build vector from mostly shuffle plus few inserting.
6177     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6178       return Sh;
6179
6180     // For SSE 4.1, use insertps to put the high elements into the low element.
6181     if (Subtarget->hasSSE41()) {
6182       SDValue Result;
6183       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6184         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6185       else
6186         Result = DAG.getUNDEF(VT);
6187
6188       for (unsigned i = 1; i < NumElems; ++i) {
6189         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6190         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6191                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6192       }
6193       return Result;
6194     }
6195
6196     // Otherwise, expand into a number of unpckl*, start by extending each of
6197     // our (non-undef) elements to the full vector width with the element in the
6198     // bottom slot of the vector (which generates no code for SSE).
6199     for (unsigned i = 0; i < NumElems; ++i) {
6200       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6201         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6202       else
6203         V[i] = DAG.getUNDEF(VT);
6204     }
6205
6206     // Next, we iteratively mix elements, e.g. for v4f32:
6207     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6208     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6209     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6210     unsigned EltStride = NumElems >> 1;
6211     while (EltStride != 0) {
6212       for (unsigned i = 0; i < EltStride; ++i) {
6213         // If V[i+EltStride] is undef and this is the first round of mixing,
6214         // then it is safe to just drop this shuffle: V[i] is already in the
6215         // right place, the one element (since it's the first round) being
6216         // inserted as undef can be dropped.  This isn't safe for successive
6217         // rounds because they will permute elements within both vectors.
6218         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6219             EltStride == NumElems/2)
6220           continue;
6221
6222         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6223       }
6224       EltStride >>= 1;
6225     }
6226     return V[0];
6227   }
6228   return SDValue();
6229 }
6230
6231 // 256-bit AVX can use the vinsertf128 instruction
6232 // to create 256-bit vectors from two other 128-bit ones.
6233 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6234   SDLoc dl(Op);
6235   MVT ResVT = Op.getSimpleValueType();
6236
6237   assert((ResVT.is256BitVector() ||
6238           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6239
6240   SDValue V1 = Op.getOperand(0);
6241   SDValue V2 = Op.getOperand(1);
6242   unsigned NumElems = ResVT.getVectorNumElements();
6243   if (ResVT.is256BitVector())
6244     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6245
6246   if (Op.getNumOperands() == 4) {
6247     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6248                                 ResVT.getVectorNumElements()/2);
6249     SDValue V3 = Op.getOperand(2);
6250     SDValue V4 = Op.getOperand(3);
6251     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6252       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6253   }
6254   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6255 }
6256
6257 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6258                                        const X86Subtarget *Subtarget,
6259                                        SelectionDAG & DAG) {
6260   SDLoc dl(Op);
6261   MVT ResVT = Op.getSimpleValueType();
6262   unsigned NumOfOperands = Op.getNumOperands();
6263
6264   assert(isPowerOf2_32(NumOfOperands) &&
6265          "Unexpected number of operands in CONCAT_VECTORS");
6266
6267   if (NumOfOperands > 2) {
6268     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6269                                   ResVT.getVectorNumElements()/2);
6270     SmallVector<SDValue, 2> Ops;
6271     for (unsigned i = 0; i < NumOfOperands/2; i++)
6272       Ops.push_back(Op.getOperand(i));
6273     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6274     Ops.clear();
6275     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6276       Ops.push_back(Op.getOperand(i));
6277     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6278     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6279   }
6280
6281   SDValue V1 = Op.getOperand(0);
6282   SDValue V2 = Op.getOperand(1);
6283   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6284   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6285
6286   if (IsZeroV1 && IsZeroV2)
6287     return getZeroVector(ResVT, Subtarget, DAG, dl);
6288
6289   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6290   SDValue Undef = DAG.getUNDEF(ResVT);
6291   unsigned NumElems = ResVT.getVectorNumElements();
6292   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6293
6294   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6295   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6296   if (IsZeroV1)
6297     return V2;
6298
6299   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6300   // Zero the upper bits of V1
6301   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6302   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6303   if (IsZeroV2)
6304     return V1;
6305   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6306 }
6307
6308 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6309                                    const X86Subtarget *Subtarget,
6310                                    SelectionDAG &DAG) {
6311   MVT VT = Op.getSimpleValueType();
6312   if (VT.getVectorElementType() == MVT::i1)
6313     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6314
6315   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6316          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6317           Op.getNumOperands() == 4)));
6318
6319   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6320   // from two other 128-bit ones.
6321
6322   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6323   return LowerAVXCONCAT_VECTORS(Op, DAG);
6324 }
6325
6326
6327 //===----------------------------------------------------------------------===//
6328 // Vector shuffle lowering
6329 //
6330 // This is an experimental code path for lowering vector shuffles on x86. It is
6331 // designed to handle arbitrary vector shuffles and blends, gracefully
6332 // degrading performance as necessary. It works hard to recognize idiomatic
6333 // shuffles and lower them to optimal instruction patterns without leaving
6334 // a framework that allows reasonably efficient handling of all vector shuffle
6335 // patterns.
6336 //===----------------------------------------------------------------------===//
6337
6338 /// \brief Tiny helper function to identify a no-op mask.
6339 ///
6340 /// This is a somewhat boring predicate function. It checks whether the mask
6341 /// array input, which is assumed to be a single-input shuffle mask of the kind
6342 /// used by the X86 shuffle instructions (not a fully general
6343 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6344 /// in-place shuffle are 'no-op's.
6345 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6346   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6347     if (Mask[i] != -1 && Mask[i] != i)
6348       return false;
6349   return true;
6350 }
6351
6352 /// \brief Helper function to classify a mask as a single-input mask.
6353 ///
6354 /// This isn't a generic single-input test because in the vector shuffle
6355 /// lowering we canonicalize single inputs to be the first input operand. This
6356 /// means we can more quickly test for a single input by only checking whether
6357 /// an input from the second operand exists. We also assume that the size of
6358 /// mask corresponds to the size of the input vectors which isn't true in the
6359 /// fully general case.
6360 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6361   for (int M : Mask)
6362     if (M >= (int)Mask.size())
6363       return false;
6364   return true;
6365 }
6366
6367 /// \brief Test whether there are elements crossing 128-bit lanes in this
6368 /// shuffle mask.
6369 ///
6370 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6371 /// and we routinely test for these.
6372 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6373   int LaneSize = 128 / VT.getScalarSizeInBits();
6374   int Size = Mask.size();
6375   for (int i = 0; i < Size; ++i)
6376     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6377       return true;
6378   return false;
6379 }
6380
6381 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6382 ///
6383 /// This checks a shuffle mask to see if it is performing the same
6384 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6385 /// that it is also not lane-crossing. It may however involve a blend from the
6386 /// same lane of a second vector.
6387 ///
6388 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6389 /// non-trivial to compute in the face of undef lanes. The representation is
6390 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6391 /// entries from both V1 and V2 inputs to the wider mask.
6392 static bool
6393 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6394                                 SmallVectorImpl<int> &RepeatedMask) {
6395   int LaneSize = 128 / VT.getScalarSizeInBits();
6396   RepeatedMask.resize(LaneSize, -1);
6397   int Size = Mask.size();
6398   for (int i = 0; i < Size; ++i) {
6399     if (Mask[i] < 0)
6400       continue;
6401     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6402       // This entry crosses lanes, so there is no way to model this shuffle.
6403       return false;
6404
6405     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6406     if (RepeatedMask[i % LaneSize] == -1)
6407       // This is the first non-undef entry in this slot of a 128-bit lane.
6408       RepeatedMask[i % LaneSize] =
6409           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6410     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6411       // Found a mismatch with the repeated mask.
6412       return false;
6413   }
6414   return true;
6415 }
6416
6417 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6418 /// arguments.
6419 ///
6420 /// This is a fast way to test a shuffle mask against a fixed pattern:
6421 ///
6422 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6423 ///
6424 /// It returns true if the mask is exactly as wide as the argument list, and
6425 /// each element of the mask is either -1 (signifying undef) or the value given
6426 /// in the argument.
6427 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6428                                 ArrayRef<int> ExpectedMask) {
6429   if (Mask.size() != ExpectedMask.size())
6430     return false;
6431
6432   int Size = Mask.size();
6433
6434   // If the values are build vectors, we can look through them to find
6435   // equivalent inputs that make the shuffles equivalent.
6436   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6437   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6438
6439   for (int i = 0; i < Size; ++i)
6440     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6441       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6442       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6443       if (!MaskBV || !ExpectedBV ||
6444           MaskBV->getOperand(Mask[i] % Size) !=
6445               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6446         return false;
6447     }
6448
6449   return true;
6450 }
6451
6452 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6453 ///
6454 /// This helper function produces an 8-bit shuffle immediate corresponding to
6455 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6456 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6457 /// example.
6458 ///
6459 /// NB: We rely heavily on "undef" masks preserving the input lane.
6460 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6461                                           SelectionDAG &DAG) {
6462   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6463   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6464   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6465   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6466   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6467
6468   unsigned Imm = 0;
6469   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6470   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6471   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6472   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6473   return DAG.getConstant(Imm, DL, MVT::i8);
6474 }
6475
6476 /// \brief Compute whether each element of a shuffle is zeroable.
6477 ///
6478 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6479 /// Either it is an undef element in the shuffle mask, the element of the input
6480 /// referenced is undef, or the element of the input referenced is known to be
6481 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6482 /// as many lanes with this technique as possible to simplify the remaining
6483 /// shuffle.
6484 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6485                                                      SDValue V1, SDValue V2) {
6486   SmallBitVector Zeroable(Mask.size(), false);
6487
6488   while (V1.getOpcode() == ISD::BITCAST)
6489     V1 = V1->getOperand(0);
6490   while (V2.getOpcode() == ISD::BITCAST)
6491     V2 = V2->getOperand(0);
6492
6493   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6494   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6495
6496   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6497     int M = Mask[i];
6498     // Handle the easy cases.
6499     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6500       Zeroable[i] = true;
6501       continue;
6502     }
6503
6504     // If this is an index into a build_vector node (which has the same number
6505     // of elements), dig out the input value and use it.
6506     SDValue V = M < Size ? V1 : V2;
6507     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6508       continue;
6509
6510     SDValue Input = V.getOperand(M % Size);
6511     // The UNDEF opcode check really should be dead code here, but not quite
6512     // worth asserting on (it isn't invalid, just unexpected).
6513     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6514       Zeroable[i] = true;
6515   }
6516
6517   return Zeroable;
6518 }
6519
6520 /// \brief Try to emit a bitmask instruction for a shuffle.
6521 ///
6522 /// This handles cases where we can model a blend exactly as a bitmask due to
6523 /// one of the inputs being zeroable.
6524 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6525                                            SDValue V2, ArrayRef<int> Mask,
6526                                            SelectionDAG &DAG) {
6527   MVT EltVT = VT.getScalarType();
6528   int NumEltBits = EltVT.getSizeInBits();
6529   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6530   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6531   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6532                                     IntEltVT);
6533   if (EltVT.isFloatingPoint()) {
6534     Zero = DAG.getBitcast(EltVT, Zero);
6535     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6536   }
6537   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6538   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6539   SDValue V;
6540   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6541     if (Zeroable[i])
6542       continue;
6543     if (Mask[i] % Size != i)
6544       return SDValue(); // Not a blend.
6545     if (!V)
6546       V = Mask[i] < Size ? V1 : V2;
6547     else if (V != (Mask[i] < Size ? V1 : V2))
6548       return SDValue(); // Can only let one input through the mask.
6549
6550     VMaskOps[i] = AllOnes;
6551   }
6552   if (!V)
6553     return SDValue(); // No non-zeroable elements!
6554
6555   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6556   V = DAG.getNode(VT.isFloatingPoint()
6557                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6558                   DL, VT, V, VMask);
6559   return V;
6560 }
6561
6562 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6563 ///
6564 /// This is used as a fallback approach when first class blend instructions are
6565 /// unavailable. Currently it is only suitable for integer vectors, but could
6566 /// be generalized for floating point vectors if desirable.
6567 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6568                                             SDValue V2, ArrayRef<int> Mask,
6569                                             SelectionDAG &DAG) {
6570   assert(VT.isInteger() && "Only supports integer vector types!");
6571   MVT EltVT = VT.getScalarType();
6572   int NumEltBits = EltVT.getSizeInBits();
6573   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6574   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6575                                     EltVT);
6576   SmallVector<SDValue, 16> MaskOps;
6577   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6578     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6579       return SDValue(); // Shuffled input!
6580     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6581   }
6582
6583   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6584   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6585   // We have to cast V2 around.
6586   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6587   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6588                                       DAG.getBitcast(MaskVT, V1Mask),
6589                                       DAG.getBitcast(MaskVT, V2)));
6590   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6591 }
6592
6593 /// \brief Try to emit a blend instruction for a shuffle.
6594 ///
6595 /// This doesn't do any checks for the availability of instructions for blending
6596 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6597 /// be matched in the backend with the type given. What it does check for is
6598 /// that the shuffle mask is in fact a blend.
6599 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6600                                          SDValue V2, ArrayRef<int> Mask,
6601                                          const X86Subtarget *Subtarget,
6602                                          SelectionDAG &DAG) {
6603   unsigned BlendMask = 0;
6604   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6605     if (Mask[i] >= Size) {
6606       if (Mask[i] != i + Size)
6607         return SDValue(); // Shuffled V2 input!
6608       BlendMask |= 1u << i;
6609       continue;
6610     }
6611     if (Mask[i] >= 0 && Mask[i] != i)
6612       return SDValue(); // Shuffled V1 input!
6613   }
6614   switch (VT.SimpleTy) {
6615   case MVT::v2f64:
6616   case MVT::v4f32:
6617   case MVT::v4f64:
6618   case MVT::v8f32:
6619     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6620                        DAG.getConstant(BlendMask, DL, MVT::i8));
6621
6622   case MVT::v4i64:
6623   case MVT::v8i32:
6624     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6625     // FALLTHROUGH
6626   case MVT::v2i64:
6627   case MVT::v4i32:
6628     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6629     // that instruction.
6630     if (Subtarget->hasAVX2()) {
6631       // Scale the blend by the number of 32-bit dwords per element.
6632       int Scale =  VT.getScalarSizeInBits() / 32;
6633       BlendMask = 0;
6634       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6635         if (Mask[i] >= Size)
6636           for (int j = 0; j < Scale; ++j)
6637             BlendMask |= 1u << (i * Scale + j);
6638
6639       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6640       V1 = DAG.getBitcast(BlendVT, V1);
6641       V2 = DAG.getBitcast(BlendVT, V2);
6642       return DAG.getBitcast(
6643           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6644                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6645     }
6646     // FALLTHROUGH
6647   case MVT::v8i16: {
6648     // For integer shuffles we need to expand the mask and cast the inputs to
6649     // v8i16s prior to blending.
6650     int Scale = 8 / VT.getVectorNumElements();
6651     BlendMask = 0;
6652     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6653       if (Mask[i] >= Size)
6654         for (int j = 0; j < Scale; ++j)
6655           BlendMask |= 1u << (i * Scale + j);
6656
6657     V1 = DAG.getBitcast(MVT::v8i16, V1);
6658     V2 = DAG.getBitcast(MVT::v8i16, V2);
6659     return DAG.getBitcast(VT,
6660                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6661                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6662   }
6663
6664   case MVT::v16i16: {
6665     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6666     SmallVector<int, 8> RepeatedMask;
6667     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6668       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6669       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6670       BlendMask = 0;
6671       for (int i = 0; i < 8; ++i)
6672         if (RepeatedMask[i] >= 16)
6673           BlendMask |= 1u << i;
6674       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6675                          DAG.getConstant(BlendMask, DL, MVT::i8));
6676     }
6677   }
6678     // FALLTHROUGH
6679   case MVT::v16i8:
6680   case MVT::v32i8: {
6681     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6682            "256-bit byte-blends require AVX2 support!");
6683
6684     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6685     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6686       return Masked;
6687
6688     // Scale the blend by the number of bytes per element.
6689     int Scale = VT.getScalarSizeInBits() / 8;
6690
6691     // This form of blend is always done on bytes. Compute the byte vector
6692     // type.
6693     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6694
6695     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6696     // mix of LLVM's code generator and the x86 backend. We tell the code
6697     // generator that boolean values in the elements of an x86 vector register
6698     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6699     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6700     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6701     // of the element (the remaining are ignored) and 0 in that high bit would
6702     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6703     // the LLVM model for boolean values in vector elements gets the relevant
6704     // bit set, it is set backwards and over constrained relative to x86's
6705     // actual model.
6706     SmallVector<SDValue, 32> VSELECTMask;
6707     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6708       for (int j = 0; j < Scale; ++j)
6709         VSELECTMask.push_back(
6710             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6711                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6712                                           MVT::i8));
6713
6714     V1 = DAG.getBitcast(BlendVT, V1);
6715     V2 = DAG.getBitcast(BlendVT, V2);
6716     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6717                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6718                                                       BlendVT, VSELECTMask),
6719                                           V1, V2));
6720   }
6721
6722   default:
6723     llvm_unreachable("Not a supported integer vector type!");
6724   }
6725 }
6726
6727 /// \brief Try to lower as a blend of elements from two inputs followed by
6728 /// a single-input permutation.
6729 ///
6730 /// This matches the pattern where we can blend elements from two inputs and
6731 /// then reduce the shuffle to a single-input permutation.
6732 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6733                                                    SDValue V2,
6734                                                    ArrayRef<int> Mask,
6735                                                    SelectionDAG &DAG) {
6736   // We build up the blend mask while checking whether a blend is a viable way
6737   // to reduce the shuffle.
6738   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6739   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6740
6741   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6742     if (Mask[i] < 0)
6743       continue;
6744
6745     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6746
6747     if (BlendMask[Mask[i] % Size] == -1)
6748       BlendMask[Mask[i] % Size] = Mask[i];
6749     else if (BlendMask[Mask[i] % Size] != Mask[i])
6750       return SDValue(); // Can't blend in the needed input!
6751
6752     PermuteMask[i] = Mask[i] % Size;
6753   }
6754
6755   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6756   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6757 }
6758
6759 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6760 /// blends and permutes.
6761 ///
6762 /// This matches the extremely common pattern for handling combined
6763 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6764 /// operations. It will try to pick the best arrangement of shuffles and
6765 /// blends.
6766 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6767                                                           SDValue V1,
6768                                                           SDValue V2,
6769                                                           ArrayRef<int> Mask,
6770                                                           SelectionDAG &DAG) {
6771   // Shuffle the input elements into the desired positions in V1 and V2 and
6772   // blend them together.
6773   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6774   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6775   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6776   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6777     if (Mask[i] >= 0 && Mask[i] < Size) {
6778       V1Mask[i] = Mask[i];
6779       BlendMask[i] = i;
6780     } else if (Mask[i] >= Size) {
6781       V2Mask[i] = Mask[i] - Size;
6782       BlendMask[i] = i + Size;
6783     }
6784
6785   // Try to lower with the simpler initial blend strategy unless one of the
6786   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6787   // shuffle may be able to fold with a load or other benefit. However, when
6788   // we'll have to do 2x as many shuffles in order to achieve this, blending
6789   // first is a better strategy.
6790   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6791     if (SDValue BlendPerm =
6792             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6793       return BlendPerm;
6794
6795   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6796   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6797   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6798 }
6799
6800 /// \brief Try to lower a vector shuffle as a byte rotation.
6801 ///
6802 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6803 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6804 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6805 /// try to generically lower a vector shuffle through such an pattern. It
6806 /// does not check for the profitability of lowering either as PALIGNR or
6807 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6808 /// This matches shuffle vectors that look like:
6809 ///
6810 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6811 ///
6812 /// Essentially it concatenates V1 and V2, shifts right by some number of
6813 /// elements, and takes the low elements as the result. Note that while this is
6814 /// specified as a *right shift* because x86 is little-endian, it is a *left
6815 /// rotate* of the vector lanes.
6816 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6817                                               SDValue V2,
6818                                               ArrayRef<int> Mask,
6819                                               const X86Subtarget *Subtarget,
6820                                               SelectionDAG &DAG) {
6821   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6822
6823   int NumElts = Mask.size();
6824   int NumLanes = VT.getSizeInBits() / 128;
6825   int NumLaneElts = NumElts / NumLanes;
6826
6827   // We need to detect various ways of spelling a rotation:
6828   //   [11, 12, 13, 14, 15,  0,  1,  2]
6829   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6830   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6831   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6832   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6833   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6834   int Rotation = 0;
6835   SDValue Lo, Hi;
6836   for (int l = 0; l < NumElts; l += NumLaneElts) {
6837     for (int i = 0; i < NumLaneElts; ++i) {
6838       if (Mask[l + i] == -1)
6839         continue;
6840       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6841
6842       // Get the mod-Size index and lane correct it.
6843       int LaneIdx = (Mask[l + i] % NumElts) - l;
6844       // Make sure it was in this lane.
6845       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6846         return SDValue();
6847
6848       // Determine where a rotated vector would have started.
6849       int StartIdx = i - LaneIdx;
6850       if (StartIdx == 0)
6851         // The identity rotation isn't interesting, stop.
6852         return SDValue();
6853
6854       // If we found the tail of a vector the rotation must be the missing
6855       // front. If we found the head of a vector, it must be how much of the
6856       // head.
6857       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6858
6859       if (Rotation == 0)
6860         Rotation = CandidateRotation;
6861       else if (Rotation != CandidateRotation)
6862         // The rotations don't match, so we can't match this mask.
6863         return SDValue();
6864
6865       // Compute which value this mask is pointing at.
6866       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6867
6868       // Compute which of the two target values this index should be assigned
6869       // to. This reflects whether the high elements are remaining or the low
6870       // elements are remaining.
6871       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6872
6873       // Either set up this value if we've not encountered it before, or check
6874       // that it remains consistent.
6875       if (!TargetV)
6876         TargetV = MaskV;
6877       else if (TargetV != MaskV)
6878         // This may be a rotation, but it pulls from the inputs in some
6879         // unsupported interleaving.
6880         return SDValue();
6881     }
6882   }
6883
6884   // Check that we successfully analyzed the mask, and normalize the results.
6885   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6886   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6887   if (!Lo)
6888     Lo = Hi;
6889   else if (!Hi)
6890     Hi = Lo;
6891
6892   // The actual rotate instruction rotates bytes, so we need to scale the
6893   // rotation based on how many bytes are in the vector lane.
6894   int Scale = 16 / NumLaneElts;
6895
6896   // SSSE3 targets can use the palignr instruction.
6897   if (Subtarget->hasSSSE3()) {
6898     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6899     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6900     Lo = DAG.getBitcast(AlignVT, Lo);
6901     Hi = DAG.getBitcast(AlignVT, Hi);
6902
6903     return DAG.getBitcast(
6904         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6905                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6906   }
6907
6908   assert(VT.getSizeInBits() == 128 &&
6909          "Rotate-based lowering only supports 128-bit lowering!");
6910   assert(Mask.size() <= 16 &&
6911          "Can shuffle at most 16 bytes in a 128-bit vector!");
6912
6913   // Default SSE2 implementation
6914   int LoByteShift = 16 - Rotation * Scale;
6915   int HiByteShift = Rotation * Scale;
6916
6917   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6918   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6919   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6920
6921   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6922                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6923   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6924                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6925   return DAG.getBitcast(VT,
6926                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6927 }
6928
6929 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6930 ///
6931 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6932 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6933 /// matches elements from one of the input vectors shuffled to the left or
6934 /// right with zeroable elements 'shifted in'. It handles both the strictly
6935 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6936 /// quad word lane.
6937 ///
6938 /// PSHL : (little-endian) left bit shift.
6939 /// [ zz, 0, zz,  2 ]
6940 /// [ -1, 4, zz, -1 ]
6941 /// PSRL : (little-endian) right bit shift.
6942 /// [  1, zz,  3, zz]
6943 /// [ -1, -1,  7, zz]
6944 /// PSLLDQ : (little-endian) left byte shift
6945 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6946 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6947 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6948 /// PSRLDQ : (little-endian) right byte shift
6949 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6950 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6951 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6952 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6953                                          SDValue V2, ArrayRef<int> Mask,
6954                                          SelectionDAG &DAG) {
6955   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6956
6957   int Size = Mask.size();
6958   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6959
6960   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6961     for (int i = 0; i < Size; i += Scale)
6962       for (int j = 0; j < Shift; ++j)
6963         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6964           return false;
6965
6966     return true;
6967   };
6968
6969   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6970     for (int i = 0; i != Size; i += Scale) {
6971       unsigned Pos = Left ? i + Shift : i;
6972       unsigned Low = Left ? i : i + Shift;
6973       unsigned Len = Scale - Shift;
6974       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6975                                       Low + (V == V1 ? 0 : Size)))
6976         return SDValue();
6977     }
6978
6979     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6980     bool ByteShift = ShiftEltBits > 64;
6981     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6982                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6983     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6984
6985     // Normalize the scale for byte shifts to still produce an i64 element
6986     // type.
6987     Scale = ByteShift ? Scale / 2 : Scale;
6988
6989     // We need to round trip through the appropriate type for the shift.
6990     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6991     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6992     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6993            "Illegal integer vector type");
6994     V = DAG.getBitcast(ShiftVT, V);
6995
6996     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6997                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6998     return DAG.getBitcast(VT, V);
6999   };
7000
7001   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7002   // keep doubling the size of the integer elements up to that. We can
7003   // then shift the elements of the integer vector by whole multiples of
7004   // their width within the elements of the larger integer vector. Test each
7005   // multiple to see if we can find a match with the moved element indices
7006   // and that the shifted in elements are all zeroable.
7007   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7008     for (int Shift = 1; Shift != Scale; ++Shift)
7009       for (bool Left : {true, false})
7010         if (CheckZeros(Shift, Scale, Left))
7011           for (SDValue V : {V1, V2})
7012             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7013               return Match;
7014
7015   // no match
7016   return SDValue();
7017 }
7018
7019 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7020 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7021                                            SDValue V2, ArrayRef<int> Mask,
7022                                            SelectionDAG &DAG) {
7023   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7024   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7025
7026   int Size = Mask.size();
7027   int HalfSize = Size / 2;
7028   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7029
7030   // Upper half must be undefined.
7031   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7032     return SDValue();
7033
7034   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7035   // Remainder of lower half result is zero and upper half is all undef.
7036   auto LowerAsEXTRQ = [&]() {
7037     // Determine the extraction length from the part of the
7038     // lower half that isn't zeroable.
7039     int Len = HalfSize;
7040     for (; Len >= 0; --Len)
7041       if (!Zeroable[Len - 1])
7042         break;
7043     assert(Len > 0 && "Zeroable shuffle mask");
7044
7045     // Attempt to match first Len sequential elements from the lower half.
7046     SDValue Src;
7047     int Idx = -1;
7048     for (int i = 0; i != Len; ++i) {
7049       int M = Mask[i];
7050       if (M < 0)
7051         continue;
7052       SDValue &V = (M < Size ? V1 : V2);
7053       M = M % Size;
7054
7055       // All mask elements must be in the lower half.
7056       if (M > HalfSize)
7057         return SDValue();
7058
7059       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7060         Src = V;
7061         Idx = M - i;
7062         continue;
7063       }
7064       return SDValue();
7065     }
7066
7067     if (Idx < 0)
7068       return SDValue();
7069
7070     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7071     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7072     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7073     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7074                        DAG.getConstant(BitLen, DL, MVT::i8),
7075                        DAG.getConstant(BitIdx, DL, MVT::i8));
7076   };
7077
7078   if (SDValue ExtrQ = LowerAsEXTRQ())
7079     return ExtrQ;
7080
7081   // INSERTQ: Extract lowest Len elements from lower half of second source and
7082   // insert over first source, starting at Idx.
7083   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7084   auto LowerAsInsertQ = [&]() {
7085     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7086       SDValue Base;
7087
7088       // Attempt to match first source from mask before insertion point.
7089       if (isUndefInRange(Mask, 0, Idx)) {
7090         /* EMPTY */
7091       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7092         Base = V1;
7093       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7094         Base = V2;
7095       } else {
7096         continue;
7097       }
7098
7099       // Extend the extraction length looking to match both the insertion of
7100       // the second source and the remaining elements of the first.
7101       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7102         SDValue Insert;
7103         int Len = Hi - Idx;
7104
7105         // Match insertion.
7106         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7107           Insert = V1;
7108         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7109           Insert = V2;
7110         } else {
7111           continue;
7112         }
7113
7114         // Match the remaining elements of the lower half.
7115         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7116           /* EMPTY */
7117         } else if ((!Base || (Base == V1)) &&
7118                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7119           Base = V1;
7120         } else if ((!Base || (Base == V2)) &&
7121                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7122                                               Size + Hi)) {
7123           Base = V2;
7124         } else {
7125           continue;
7126         }
7127
7128         // We may not have a base (first source) - this can safely be undefined.
7129         if (!Base)
7130           Base = DAG.getUNDEF(VT);
7131
7132         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7133         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7134         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7135                            DAG.getConstant(BitLen, DL, MVT::i8),
7136                            DAG.getConstant(BitIdx, DL, MVT::i8));
7137       }
7138     }
7139
7140     return SDValue();
7141   };
7142
7143   if (SDValue InsertQ = LowerAsInsertQ())
7144     return InsertQ;
7145
7146   return SDValue();
7147 }
7148
7149 /// \brief Lower a vector shuffle as a zero or any extension.
7150 ///
7151 /// Given a specific number of elements, element bit width, and extension
7152 /// stride, produce either a zero or any extension based on the available
7153 /// features of the subtarget.
7154 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7155     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7156     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7157   assert(Scale > 1 && "Need a scale to extend.");
7158   int NumElements = VT.getVectorNumElements();
7159   int EltBits = VT.getScalarSizeInBits();
7160   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7161          "Only 8, 16, and 32 bit elements can be extended.");
7162   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7163
7164   // Found a valid zext mask! Try various lowering strategies based on the
7165   // input type and available ISA extensions.
7166   if (Subtarget->hasSSE41()) {
7167     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7168                                  NumElements / Scale);
7169     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7170   }
7171
7172   // For any extends we can cheat for larger element sizes and use shuffle
7173   // instructions that can fold with a load and/or copy.
7174   if (AnyExt && EltBits == 32) {
7175     int PSHUFDMask[4] = {0, -1, 1, -1};
7176     return DAG.getBitcast(
7177         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7178                         DAG.getBitcast(MVT::v4i32, InputV),
7179                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7180   }
7181   if (AnyExt && EltBits == 16 && Scale > 2) {
7182     int PSHUFDMask[4] = {0, -1, 0, -1};
7183     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7184                          DAG.getBitcast(MVT::v4i32, InputV),
7185                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7186     int PSHUFHWMask[4] = {1, -1, -1, -1};
7187     return DAG.getBitcast(
7188         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7189                         DAG.getBitcast(MVT::v8i16, InputV),
7190                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7191   }
7192
7193   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7194   // to 64-bits.
7195   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7196     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7197     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7198
7199     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7200                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7201                                          DAG.getConstant(EltBits, DL, MVT::i8),
7202                                          DAG.getConstant(0, DL, MVT::i8)));
7203     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7204       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7205
7206     SDValue Hi =
7207         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7208                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7209                                 DAG.getConstant(EltBits, DL, MVT::i8),
7210                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7211     return DAG.getNode(ISD::BITCAST, DL, VT,
7212                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7213   }
7214
7215   // If this would require more than 2 unpack instructions to expand, use
7216   // pshufb when available. We can only use more than 2 unpack instructions
7217   // when zero extending i8 elements which also makes it easier to use pshufb.
7218   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7219     assert(NumElements == 16 && "Unexpected byte vector width!");
7220     SDValue PSHUFBMask[16];
7221     for (int i = 0; i < 16; ++i)
7222       PSHUFBMask[i] =
7223           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7224     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7225     return DAG.getBitcast(VT,
7226                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7227                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7228                                                   MVT::v16i8, PSHUFBMask)));
7229   }
7230
7231   // Otherwise emit a sequence of unpacks.
7232   do {
7233     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7234     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7235                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7236     InputV = DAG.getBitcast(InputVT, InputV);
7237     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7238     Scale /= 2;
7239     EltBits *= 2;
7240     NumElements /= 2;
7241   } while (Scale > 1);
7242   return DAG.getBitcast(VT, InputV);
7243 }
7244
7245 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7246 ///
7247 /// This routine will try to do everything in its power to cleverly lower
7248 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7249 /// check for the profitability of this lowering,  it tries to aggressively
7250 /// match this pattern. It will use all of the micro-architectural details it
7251 /// can to emit an efficient lowering. It handles both blends with all-zero
7252 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7253 /// masking out later).
7254 ///
7255 /// The reason we have dedicated lowering for zext-style shuffles is that they
7256 /// are both incredibly common and often quite performance sensitive.
7257 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7258     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7259     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7260   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7261
7262   int Bits = VT.getSizeInBits();
7263   int NumElements = VT.getVectorNumElements();
7264   assert(VT.getScalarSizeInBits() <= 32 &&
7265          "Exceeds 32-bit integer zero extension limit");
7266   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7267
7268   // Define a helper function to check a particular ext-scale and lower to it if
7269   // valid.
7270   auto Lower = [&](int Scale) -> SDValue {
7271     SDValue InputV;
7272     bool AnyExt = true;
7273     for (int i = 0; i < NumElements; ++i) {
7274       if (Mask[i] == -1)
7275         continue; // Valid anywhere but doesn't tell us anything.
7276       if (i % Scale != 0) {
7277         // Each of the extended elements need to be zeroable.
7278         if (!Zeroable[i])
7279           return SDValue();
7280
7281         // We no longer are in the anyext case.
7282         AnyExt = false;
7283         continue;
7284       }
7285
7286       // Each of the base elements needs to be consecutive indices into the
7287       // same input vector.
7288       SDValue V = Mask[i] < NumElements ? V1 : V2;
7289       if (!InputV)
7290         InputV = V;
7291       else if (InputV != V)
7292         return SDValue(); // Flip-flopping inputs.
7293
7294       if (Mask[i] % NumElements != i / Scale)
7295         return SDValue(); // Non-consecutive strided elements.
7296     }
7297
7298     // If we fail to find an input, we have a zero-shuffle which should always
7299     // have already been handled.
7300     // FIXME: Maybe handle this here in case during blending we end up with one?
7301     if (!InputV)
7302       return SDValue();
7303
7304     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7305         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7306   };
7307
7308   // The widest scale possible for extending is to a 64-bit integer.
7309   assert(Bits % 64 == 0 &&
7310          "The number of bits in a vector must be divisible by 64 on x86!");
7311   int NumExtElements = Bits / 64;
7312
7313   // Each iteration, try extending the elements half as much, but into twice as
7314   // many elements.
7315   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7316     assert(NumElements % NumExtElements == 0 &&
7317            "The input vector size must be divisible by the extended size.");
7318     if (SDValue V = Lower(NumElements / NumExtElements))
7319       return V;
7320   }
7321
7322   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7323   if (Bits != 128)
7324     return SDValue();
7325
7326   // Returns one of the source operands if the shuffle can be reduced to a
7327   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7328   auto CanZExtLowHalf = [&]() {
7329     for (int i = NumElements / 2; i != NumElements; ++i)
7330       if (!Zeroable[i])
7331         return SDValue();
7332     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7333       return V1;
7334     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7335       return V2;
7336     return SDValue();
7337   };
7338
7339   if (SDValue V = CanZExtLowHalf()) {
7340     V = DAG.getBitcast(MVT::v2i64, V);
7341     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7342     return DAG.getBitcast(VT, V);
7343   }
7344
7345   // No viable ext lowering found.
7346   return SDValue();
7347 }
7348
7349 /// \brief Try to get a scalar value for a specific element of a vector.
7350 ///
7351 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7352 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7353                                               SelectionDAG &DAG) {
7354   MVT VT = V.getSimpleValueType();
7355   MVT EltVT = VT.getVectorElementType();
7356   while (V.getOpcode() == ISD::BITCAST)
7357     V = V.getOperand(0);
7358   // If the bitcasts shift the element size, we can't extract an equivalent
7359   // element from it.
7360   MVT NewVT = V.getSimpleValueType();
7361   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7362     return SDValue();
7363
7364   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7365       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7366     // Ensure the scalar operand is the same size as the destination.
7367     // FIXME: Add support for scalar truncation where possible.
7368     SDValue S = V.getOperand(Idx);
7369     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7370       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7371   }
7372
7373   return SDValue();
7374 }
7375
7376 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7377 ///
7378 /// This is particularly important because the set of instructions varies
7379 /// significantly based on whether the operand is a load or not.
7380 static bool isShuffleFoldableLoad(SDValue V) {
7381   while (V.getOpcode() == ISD::BITCAST)
7382     V = V.getOperand(0);
7383
7384   return ISD::isNON_EXTLoad(V.getNode());
7385 }
7386
7387 /// \brief Try to lower insertion of a single element into a zero vector.
7388 ///
7389 /// This is a common pattern that we have especially efficient patterns to lower
7390 /// across all subtarget feature sets.
7391 static SDValue lowerVectorShuffleAsElementInsertion(
7392     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7393     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7394   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7395   MVT ExtVT = VT;
7396   MVT EltVT = VT.getVectorElementType();
7397
7398   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7399                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7400                 Mask.begin();
7401   bool IsV1Zeroable = true;
7402   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7403     if (i != V2Index && !Zeroable[i]) {
7404       IsV1Zeroable = false;
7405       break;
7406     }
7407
7408   // Check for a single input from a SCALAR_TO_VECTOR node.
7409   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7410   // all the smarts here sunk into that routine. However, the current
7411   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7412   // vector shuffle lowering is dead.
7413   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7414                                                DAG);
7415   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7416     // We need to zext the scalar if it is smaller than an i32.
7417     V2S = DAG.getBitcast(EltVT, V2S);
7418     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7419       // Using zext to expand a narrow element won't work for non-zero
7420       // insertions.
7421       if (!IsV1Zeroable)
7422         return SDValue();
7423
7424       // Zero-extend directly to i32.
7425       ExtVT = MVT::v4i32;
7426       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7427     }
7428     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7429   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7430              EltVT == MVT::i16) {
7431     // Either not inserting from the low element of the input or the input
7432     // element size is too small to use VZEXT_MOVL to clear the high bits.
7433     return SDValue();
7434   }
7435
7436   if (!IsV1Zeroable) {
7437     // If V1 can't be treated as a zero vector we have fewer options to lower
7438     // this. We can't support integer vectors or non-zero targets cheaply, and
7439     // the V1 elements can't be permuted in any way.
7440     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7441     if (!VT.isFloatingPoint() || V2Index != 0)
7442       return SDValue();
7443     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7444     V1Mask[V2Index] = -1;
7445     if (!isNoopShuffleMask(V1Mask))
7446       return SDValue();
7447     // This is essentially a special case blend operation, but if we have
7448     // general purpose blend operations, they are always faster. Bail and let
7449     // the rest of the lowering handle these as blends.
7450     if (Subtarget->hasSSE41())
7451       return SDValue();
7452
7453     // Otherwise, use MOVSD or MOVSS.
7454     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7455            "Only two types of floating point element types to handle!");
7456     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7457                        ExtVT, V1, V2);
7458   }
7459
7460   // This lowering only works for the low element with floating point vectors.
7461   if (VT.isFloatingPoint() && V2Index != 0)
7462     return SDValue();
7463
7464   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7465   if (ExtVT != VT)
7466     V2 = DAG.getBitcast(VT, V2);
7467
7468   if (V2Index != 0) {
7469     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7470     // the desired position. Otherwise it is more efficient to do a vector
7471     // shift left. We know that we can do a vector shift left because all
7472     // the inputs are zero.
7473     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7474       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7475       V2Shuffle[V2Index] = 0;
7476       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7477     } else {
7478       V2 = DAG.getBitcast(MVT::v2i64, V2);
7479       V2 = DAG.getNode(
7480           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7481           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7482                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7483                               DAG.getDataLayout(), VT)));
7484       V2 = DAG.getBitcast(VT, V2);
7485     }
7486   }
7487   return V2;
7488 }
7489
7490 /// \brief Try to lower broadcast of a single element.
7491 ///
7492 /// For convenience, this code also bundles all of the subtarget feature set
7493 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7494 /// a convenient way to factor it out.
7495 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7496                                              ArrayRef<int> Mask,
7497                                              const X86Subtarget *Subtarget,
7498                                              SelectionDAG &DAG) {
7499   if (!Subtarget->hasAVX())
7500     return SDValue();
7501   if (VT.isInteger() && !Subtarget->hasAVX2())
7502     return SDValue();
7503
7504   // Check that the mask is a broadcast.
7505   int BroadcastIdx = -1;
7506   for (int M : Mask)
7507     if (M >= 0 && BroadcastIdx == -1)
7508       BroadcastIdx = M;
7509     else if (M >= 0 && M != BroadcastIdx)
7510       return SDValue();
7511
7512   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7513                                             "a sorted mask where the broadcast "
7514                                             "comes from V1.");
7515
7516   // Go up the chain of (vector) values to find a scalar load that we can
7517   // combine with the broadcast.
7518   for (;;) {
7519     switch (V.getOpcode()) {
7520     case ISD::CONCAT_VECTORS: {
7521       int OperandSize = Mask.size() / V.getNumOperands();
7522       V = V.getOperand(BroadcastIdx / OperandSize);
7523       BroadcastIdx %= OperandSize;
7524       continue;
7525     }
7526
7527     case ISD::INSERT_SUBVECTOR: {
7528       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7529       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7530       if (!ConstantIdx)
7531         break;
7532
7533       int BeginIdx = (int)ConstantIdx->getZExtValue();
7534       int EndIdx =
7535           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7536       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7537         BroadcastIdx -= BeginIdx;
7538         V = VInner;
7539       } else {
7540         V = VOuter;
7541       }
7542       continue;
7543     }
7544     }
7545     break;
7546   }
7547
7548   // Check if this is a broadcast of a scalar. We special case lowering
7549   // for scalars so that we can more effectively fold with loads.
7550   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7551       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7552     V = V.getOperand(BroadcastIdx);
7553
7554     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7555     // Only AVX2 has register broadcasts.
7556     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7557       return SDValue();
7558   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7559     // We can't broadcast from a vector register without AVX2, and we can only
7560     // broadcast from the zero-element of a vector register.
7561     return SDValue();
7562   }
7563
7564   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7565 }
7566
7567 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7568 // INSERTPS when the V1 elements are already in the correct locations
7569 // because otherwise we can just always use two SHUFPS instructions which
7570 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7571 // perform INSERTPS if a single V1 element is out of place and all V2
7572 // elements are zeroable.
7573 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7574                                             ArrayRef<int> Mask,
7575                                             SelectionDAG &DAG) {
7576   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7577   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7578   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7579   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7580
7581   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7582
7583   unsigned ZMask = 0;
7584   int V1DstIndex = -1;
7585   int V2DstIndex = -1;
7586   bool V1UsedInPlace = false;
7587
7588   for (int i = 0; i < 4; ++i) {
7589     // Synthesize a zero mask from the zeroable elements (includes undefs).
7590     if (Zeroable[i]) {
7591       ZMask |= 1 << i;
7592       continue;
7593     }
7594
7595     // Flag if we use any V1 inputs in place.
7596     if (i == Mask[i]) {
7597       V1UsedInPlace = true;
7598       continue;
7599     }
7600
7601     // We can only insert a single non-zeroable element.
7602     if (V1DstIndex != -1 || V2DstIndex != -1)
7603       return SDValue();
7604
7605     if (Mask[i] < 4) {
7606       // V1 input out of place for insertion.
7607       V1DstIndex = i;
7608     } else {
7609       // V2 input for insertion.
7610       V2DstIndex = i;
7611     }
7612   }
7613
7614   // Don't bother if we have no (non-zeroable) element for insertion.
7615   if (V1DstIndex == -1 && V2DstIndex == -1)
7616     return SDValue();
7617
7618   // Determine element insertion src/dst indices. The src index is from the
7619   // start of the inserted vector, not the start of the concatenated vector.
7620   unsigned V2SrcIndex = 0;
7621   if (V1DstIndex != -1) {
7622     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7623     // and don't use the original V2 at all.
7624     V2SrcIndex = Mask[V1DstIndex];
7625     V2DstIndex = V1DstIndex;
7626     V2 = V1;
7627   } else {
7628     V2SrcIndex = Mask[V2DstIndex] - 4;
7629   }
7630
7631   // If no V1 inputs are used in place, then the result is created only from
7632   // the zero mask and the V2 insertion - so remove V1 dependency.
7633   if (!V1UsedInPlace)
7634     V1 = DAG.getUNDEF(MVT::v4f32);
7635
7636   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7637   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7638
7639   // Insert the V2 element into the desired position.
7640   SDLoc DL(Op);
7641   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7642                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7643 }
7644
7645 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7646 /// UNPCK instruction.
7647 ///
7648 /// This specifically targets cases where we end up with alternating between
7649 /// the two inputs, and so can permute them into something that feeds a single
7650 /// UNPCK instruction. Note that this routine only targets integer vectors
7651 /// because for floating point vectors we have a generalized SHUFPS lowering
7652 /// strategy that handles everything that doesn't *exactly* match an unpack,
7653 /// making this clever lowering unnecessary.
7654 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7655                                           SDValue V2, ArrayRef<int> Mask,
7656                                           SelectionDAG &DAG) {
7657   assert(!VT.isFloatingPoint() &&
7658          "This routine only supports integer vectors.");
7659   assert(!isSingleInputShuffleMask(Mask) &&
7660          "This routine should only be used when blending two inputs.");
7661   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7662
7663   int Size = Mask.size();
7664
7665   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7666     return M >= 0 && M % Size < Size / 2;
7667   });
7668   int NumHiInputs = std::count_if(
7669       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7670
7671   bool UnpackLo = NumLoInputs >= NumHiInputs;
7672
7673   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7674     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7675     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7676
7677     for (int i = 0; i < Size; ++i) {
7678       if (Mask[i] < 0)
7679         continue;
7680
7681       // Each element of the unpack contains Scale elements from this mask.
7682       int UnpackIdx = i / Scale;
7683
7684       // We only handle the case where V1 feeds the first slots of the unpack.
7685       // We rely on canonicalization to ensure this is the case.
7686       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7687         return SDValue();
7688
7689       // Setup the mask for this input. The indexing is tricky as we have to
7690       // handle the unpack stride.
7691       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7692       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7693           Mask[i] % Size;
7694     }
7695
7696     // If we will have to shuffle both inputs to use the unpack, check whether
7697     // we can just unpack first and shuffle the result. If so, skip this unpack.
7698     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7699         !isNoopShuffleMask(V2Mask))
7700       return SDValue();
7701
7702     // Shuffle the inputs into place.
7703     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7704     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7705
7706     // Cast the inputs to the type we will use to unpack them.
7707     V1 = DAG.getBitcast(UnpackVT, V1);
7708     V2 = DAG.getBitcast(UnpackVT, V2);
7709
7710     // Unpack the inputs and cast the result back to the desired type.
7711     return DAG.getBitcast(
7712         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7713                         UnpackVT, V1, V2));
7714   };
7715
7716   // We try each unpack from the largest to the smallest to try and find one
7717   // that fits this mask.
7718   int OrigNumElements = VT.getVectorNumElements();
7719   int OrigScalarSize = VT.getScalarSizeInBits();
7720   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7721     int Scale = ScalarSize / OrigScalarSize;
7722     int NumElements = OrigNumElements / Scale;
7723     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7724     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7725       return Unpack;
7726   }
7727
7728   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7729   // initial unpack.
7730   if (NumLoInputs == 0 || NumHiInputs == 0) {
7731     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7732            "We have to have *some* inputs!");
7733     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7734
7735     // FIXME: We could consider the total complexity of the permute of each
7736     // possible unpacking. Or at the least we should consider how many
7737     // half-crossings are created.
7738     // FIXME: We could consider commuting the unpacks.
7739
7740     SmallVector<int, 32> PermMask;
7741     PermMask.assign(Size, -1);
7742     for (int i = 0; i < Size; ++i) {
7743       if (Mask[i] < 0)
7744         continue;
7745
7746       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7747
7748       PermMask[i] =
7749           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7750     }
7751     return DAG.getVectorShuffle(
7752         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7753                             DL, VT, V1, V2),
7754         DAG.getUNDEF(VT), PermMask);
7755   }
7756
7757   return SDValue();
7758 }
7759
7760 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7761 ///
7762 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7763 /// support for floating point shuffles but not integer shuffles. These
7764 /// instructions will incur a domain crossing penalty on some chips though so
7765 /// it is better to avoid lowering through this for integer vectors where
7766 /// possible.
7767 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7768                                        const X86Subtarget *Subtarget,
7769                                        SelectionDAG &DAG) {
7770   SDLoc DL(Op);
7771   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7772   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7773   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7774   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7775   ArrayRef<int> Mask = SVOp->getMask();
7776   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7777
7778   if (isSingleInputShuffleMask(Mask)) {
7779     // Use low duplicate instructions for masks that match their pattern.
7780     if (Subtarget->hasSSE3())
7781       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7782         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7783
7784     // Straight shuffle of a single input vector. Simulate this by using the
7785     // single input as both of the "inputs" to this instruction..
7786     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7787
7788     if (Subtarget->hasAVX()) {
7789       // If we have AVX, we can use VPERMILPS which will allow folding a load
7790       // into the shuffle.
7791       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7792                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7793     }
7794
7795     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7796                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7797   }
7798   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7799   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7800
7801   // If we have a single input, insert that into V1 if we can do so cheaply.
7802   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7803     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7804             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7805       return Insertion;
7806     // Try inverting the insertion since for v2 masks it is easy to do and we
7807     // can't reliably sort the mask one way or the other.
7808     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7809                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7810     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7811             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7812       return Insertion;
7813   }
7814
7815   // Try to use one of the special instruction patterns to handle two common
7816   // blend patterns if a zero-blend above didn't work.
7817   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7818       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7819     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7820       // We can either use a special instruction to load over the low double or
7821       // to move just the low double.
7822       return DAG.getNode(
7823           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7824           DL, MVT::v2f64, V2,
7825           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7826
7827   if (Subtarget->hasSSE41())
7828     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7829                                                   Subtarget, DAG))
7830       return Blend;
7831
7832   // Use dedicated unpack instructions for masks that match their pattern.
7833   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7834     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7835   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7836     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7837
7838   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7839   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7840                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7841 }
7842
7843 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7844 ///
7845 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7846 /// the integer unit to minimize domain crossing penalties. However, for blends
7847 /// it falls back to the floating point shuffle operation with appropriate bit
7848 /// casting.
7849 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7850                                        const X86Subtarget *Subtarget,
7851                                        SelectionDAG &DAG) {
7852   SDLoc DL(Op);
7853   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7854   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7855   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7856   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7857   ArrayRef<int> Mask = SVOp->getMask();
7858   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7859
7860   if (isSingleInputShuffleMask(Mask)) {
7861     // Check for being able to broadcast a single element.
7862     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7863                                                           Mask, Subtarget, DAG))
7864       return Broadcast;
7865
7866     // Straight shuffle of a single input vector. For everything from SSE2
7867     // onward this has a single fast instruction with no scary immediates.
7868     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7869     V1 = DAG.getBitcast(MVT::v4i32, V1);
7870     int WidenedMask[4] = {
7871         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7872         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7873     return DAG.getBitcast(
7874         MVT::v2i64,
7875         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7876                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7877   }
7878   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7879   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7880   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7881   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7882
7883   // If we have a blend of two PACKUS operations an the blend aligns with the
7884   // low and half halves, we can just merge the PACKUS operations. This is
7885   // particularly important as it lets us merge shuffles that this routine itself
7886   // creates.
7887   auto GetPackNode = [](SDValue V) {
7888     while (V.getOpcode() == ISD::BITCAST)
7889       V = V.getOperand(0);
7890
7891     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7892   };
7893   if (SDValue V1Pack = GetPackNode(V1))
7894     if (SDValue V2Pack = GetPackNode(V2))
7895       return DAG.getBitcast(MVT::v2i64,
7896                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7897                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7898                                                      : V1Pack.getOperand(1),
7899                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7900                                                      : V2Pack.getOperand(1)));
7901
7902   // Try to use shift instructions.
7903   if (SDValue Shift =
7904           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7905     return Shift;
7906
7907   // When loading a scalar and then shuffling it into a vector we can often do
7908   // the insertion cheaply.
7909   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7910           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7911     return Insertion;
7912   // Try inverting the insertion since for v2 masks it is easy to do and we
7913   // can't reliably sort the mask one way or the other.
7914   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7915   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7916           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7917     return Insertion;
7918
7919   // We have different paths for blend lowering, but they all must use the
7920   // *exact* same predicate.
7921   bool IsBlendSupported = Subtarget->hasSSE41();
7922   if (IsBlendSupported)
7923     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7924                                                   Subtarget, DAG))
7925       return Blend;
7926
7927   // Use dedicated unpack instructions for masks that match their pattern.
7928   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7929     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7930   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7931     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7932
7933   // Try to use byte rotation instructions.
7934   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7935   if (Subtarget->hasSSSE3())
7936     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7937             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7938       return Rotate;
7939
7940   // If we have direct support for blends, we should lower by decomposing into
7941   // a permute. That will be faster than the domain cross.
7942   if (IsBlendSupported)
7943     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7944                                                       Mask, DAG);
7945
7946   // We implement this with SHUFPD which is pretty lame because it will likely
7947   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7948   // However, all the alternatives are still more cycles and newer chips don't
7949   // have this problem. It would be really nice if x86 had better shuffles here.
7950   V1 = DAG.getBitcast(MVT::v2f64, V1);
7951   V2 = DAG.getBitcast(MVT::v2f64, V2);
7952   return DAG.getBitcast(MVT::v2i64,
7953                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7954 }
7955
7956 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7957 ///
7958 /// This is used to disable more specialized lowerings when the shufps lowering
7959 /// will happen to be efficient.
7960 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7961   // This routine only handles 128-bit shufps.
7962   assert(Mask.size() == 4 && "Unsupported mask size!");
7963
7964   // To lower with a single SHUFPS we need to have the low half and high half
7965   // each requiring a single input.
7966   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7967     return false;
7968   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7969     return false;
7970
7971   return true;
7972 }
7973
7974 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7975 ///
7976 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7977 /// It makes no assumptions about whether this is the *best* lowering, it simply
7978 /// uses it.
7979 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7980                                             ArrayRef<int> Mask, SDValue V1,
7981                                             SDValue V2, SelectionDAG &DAG) {
7982   SDValue LowV = V1, HighV = V2;
7983   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7984
7985   int NumV2Elements =
7986       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7987
7988   if (NumV2Elements == 1) {
7989     int V2Index =
7990         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7991         Mask.begin();
7992
7993     // Compute the index adjacent to V2Index and in the same half by toggling
7994     // the low bit.
7995     int V2AdjIndex = V2Index ^ 1;
7996
7997     if (Mask[V2AdjIndex] == -1) {
7998       // Handles all the cases where we have a single V2 element and an undef.
7999       // This will only ever happen in the high lanes because we commute the
8000       // vector otherwise.
8001       if (V2Index < 2)
8002         std::swap(LowV, HighV);
8003       NewMask[V2Index] -= 4;
8004     } else {
8005       // Handle the case where the V2 element ends up adjacent to a V1 element.
8006       // To make this work, blend them together as the first step.
8007       int V1Index = V2AdjIndex;
8008       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8009       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8010                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8011
8012       // Now proceed to reconstruct the final blend as we have the necessary
8013       // high or low half formed.
8014       if (V2Index < 2) {
8015         LowV = V2;
8016         HighV = V1;
8017       } else {
8018         HighV = V2;
8019       }
8020       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8021       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8022     }
8023   } else if (NumV2Elements == 2) {
8024     if (Mask[0] < 4 && Mask[1] < 4) {
8025       // Handle the easy case where we have V1 in the low lanes and V2 in the
8026       // high lanes.
8027       NewMask[2] -= 4;
8028       NewMask[3] -= 4;
8029     } else if (Mask[2] < 4 && Mask[3] < 4) {
8030       // We also handle the reversed case because this utility may get called
8031       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8032       // arrange things in the right direction.
8033       NewMask[0] -= 4;
8034       NewMask[1] -= 4;
8035       HighV = V1;
8036       LowV = V2;
8037     } else {
8038       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8039       // trying to place elements directly, just blend them and set up the final
8040       // shuffle to place them.
8041
8042       // The first two blend mask elements are for V1, the second two are for
8043       // V2.
8044       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8045                           Mask[2] < 4 ? Mask[2] : Mask[3],
8046                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8047                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8048       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8049                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8050
8051       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8052       // a blend.
8053       LowV = HighV = V1;
8054       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8055       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8056       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8057       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8058     }
8059   }
8060   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8061                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8062 }
8063
8064 /// \brief Lower 4-lane 32-bit floating point shuffles.
8065 ///
8066 /// Uses instructions exclusively from the floating point unit to minimize
8067 /// domain crossing penalties, as these are sufficient to implement all v4f32
8068 /// shuffles.
8069 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8070                                        const X86Subtarget *Subtarget,
8071                                        SelectionDAG &DAG) {
8072   SDLoc DL(Op);
8073   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8074   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8075   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8076   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8077   ArrayRef<int> Mask = SVOp->getMask();
8078   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8079
8080   int NumV2Elements =
8081       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8082
8083   if (NumV2Elements == 0) {
8084     // Check for being able to broadcast a single element.
8085     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8086                                                           Mask, Subtarget, DAG))
8087       return Broadcast;
8088
8089     // Use even/odd duplicate instructions for masks that match their pattern.
8090     if (Subtarget->hasSSE3()) {
8091       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8092         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8093       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8094         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8095     }
8096
8097     if (Subtarget->hasAVX()) {
8098       // If we have AVX, we can use VPERMILPS which will allow folding a load
8099       // into the shuffle.
8100       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8101                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8102     }
8103
8104     // Otherwise, use a straight shuffle of a single input vector. We pass the
8105     // input vector to both operands to simulate this with a SHUFPS.
8106     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8107                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8108   }
8109
8110   // There are special ways we can lower some single-element blends. However, we
8111   // have custom ways we can lower more complex single-element blends below that
8112   // we defer to if both this and BLENDPS fail to match, so restrict this to
8113   // when the V2 input is targeting element 0 of the mask -- that is the fast
8114   // case here.
8115   if (NumV2Elements == 1 && Mask[0] >= 4)
8116     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8117                                                          Mask, Subtarget, DAG))
8118       return V;
8119
8120   if (Subtarget->hasSSE41()) {
8121     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8122                                                   Subtarget, DAG))
8123       return Blend;
8124
8125     // Use INSERTPS if we can complete the shuffle efficiently.
8126     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8127       return V;
8128
8129     if (!isSingleSHUFPSMask(Mask))
8130       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8131               DL, MVT::v4f32, V1, V2, Mask, DAG))
8132         return BlendPerm;
8133   }
8134
8135   // Use dedicated unpack instructions for masks that match their pattern.
8136   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8137     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8138   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8139     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8140   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8141     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8142   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8143     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8144
8145   // Otherwise fall back to a SHUFPS lowering strategy.
8146   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8147 }
8148
8149 /// \brief Lower 4-lane i32 vector shuffles.
8150 ///
8151 /// We try to handle these with integer-domain shuffles where we can, but for
8152 /// blends we use the floating point domain blend instructions.
8153 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8154                                        const X86Subtarget *Subtarget,
8155                                        SelectionDAG &DAG) {
8156   SDLoc DL(Op);
8157   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8158   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8159   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8160   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8161   ArrayRef<int> Mask = SVOp->getMask();
8162   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8163
8164   // Whenever we can lower this as a zext, that instruction is strictly faster
8165   // than any alternative. It also allows us to fold memory operands into the
8166   // shuffle in many cases.
8167   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8168                                                          Mask, Subtarget, DAG))
8169     return ZExt;
8170
8171   int NumV2Elements =
8172       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8173
8174   if (NumV2Elements == 0) {
8175     // Check for being able to broadcast a single element.
8176     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8177                                                           Mask, Subtarget, DAG))
8178       return Broadcast;
8179
8180     // Straight shuffle of a single input vector. For everything from SSE2
8181     // onward this has a single fast instruction with no scary immediates.
8182     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8183     // but we aren't actually going to use the UNPCK instruction because doing
8184     // so prevents folding a load into this instruction or making a copy.
8185     const int UnpackLoMask[] = {0, 0, 1, 1};
8186     const int UnpackHiMask[] = {2, 2, 3, 3};
8187     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8188       Mask = UnpackLoMask;
8189     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8190       Mask = UnpackHiMask;
8191
8192     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8193                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8194   }
8195
8196   // Try to use shift instructions.
8197   if (SDValue Shift =
8198           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8199     return Shift;
8200
8201   // There are special ways we can lower some single-element blends.
8202   if (NumV2Elements == 1)
8203     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8204                                                          Mask, Subtarget, DAG))
8205       return V;
8206
8207   // We have different paths for blend lowering, but they all must use the
8208   // *exact* same predicate.
8209   bool IsBlendSupported = Subtarget->hasSSE41();
8210   if (IsBlendSupported)
8211     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8212                                                   Subtarget, DAG))
8213       return Blend;
8214
8215   if (SDValue Masked =
8216           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8217     return Masked;
8218
8219   // Use dedicated unpack instructions for masks that match their pattern.
8220   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8221     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8222   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8223     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8224   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8225     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8226   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8227     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8228
8229   // Try to use byte rotation instructions.
8230   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8231   if (Subtarget->hasSSSE3())
8232     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8233             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8234       return Rotate;
8235
8236   // If we have direct support for blends, we should lower by decomposing into
8237   // a permute. That will be faster than the domain cross.
8238   if (IsBlendSupported)
8239     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8240                                                       Mask, DAG);
8241
8242   // Try to lower by permuting the inputs into an unpack instruction.
8243   if (SDValue Unpack =
8244           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8245     return Unpack;
8246
8247   // We implement this with SHUFPS because it can blend from two vectors.
8248   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8249   // up the inputs, bypassing domain shift penalties that we would encur if we
8250   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8251   // relevant.
8252   return DAG.getBitcast(
8253       MVT::v4i32,
8254       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8255                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8256 }
8257
8258 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8259 /// shuffle lowering, and the most complex part.
8260 ///
8261 /// The lowering strategy is to try to form pairs of input lanes which are
8262 /// targeted at the same half of the final vector, and then use a dword shuffle
8263 /// to place them onto the right half, and finally unpack the paired lanes into
8264 /// their final position.
8265 ///
8266 /// The exact breakdown of how to form these dword pairs and align them on the
8267 /// correct sides is really tricky. See the comments within the function for
8268 /// more of the details.
8269 ///
8270 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8271 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8272 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8273 /// vector, form the analogous 128-bit 8-element Mask.
8274 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8275     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8276     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8277   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8278   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8279
8280   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8281   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8282   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8283
8284   SmallVector<int, 4> LoInputs;
8285   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8286                [](int M) { return M >= 0; });
8287   std::sort(LoInputs.begin(), LoInputs.end());
8288   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8289   SmallVector<int, 4> HiInputs;
8290   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8291                [](int M) { return M >= 0; });
8292   std::sort(HiInputs.begin(), HiInputs.end());
8293   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8294   int NumLToL =
8295       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8296   int NumHToL = LoInputs.size() - NumLToL;
8297   int NumLToH =
8298       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8299   int NumHToH = HiInputs.size() - NumLToH;
8300   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8301   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8302   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8303   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8304
8305   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8306   // such inputs we can swap two of the dwords across the half mark and end up
8307   // with <=2 inputs to each half in each half. Once there, we can fall through
8308   // to the generic code below. For example:
8309   //
8310   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8311   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8312   //
8313   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8314   // and an existing 2-into-2 on the other half. In this case we may have to
8315   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8316   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8317   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8318   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8319   // half than the one we target for fixing) will be fixed when we re-enter this
8320   // path. We will also combine away any sequence of PSHUFD instructions that
8321   // result into a single instruction. Here is an example of the tricky case:
8322   //
8323   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8324   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8325   //
8326   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8327   //
8328   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8329   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8330   //
8331   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8332   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8333   //
8334   // The result is fine to be handled by the generic logic.
8335   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8336                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8337                           int AOffset, int BOffset) {
8338     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8339            "Must call this with A having 3 or 1 inputs from the A half.");
8340     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8341            "Must call this with B having 1 or 3 inputs from the B half.");
8342     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8343            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8344
8345     bool ThreeAInputs = AToAInputs.size() == 3;
8346
8347     // Compute the index of dword with only one word among the three inputs in
8348     // a half by taking the sum of the half with three inputs and subtracting
8349     // the sum of the actual three inputs. The difference is the remaining
8350     // slot.
8351     int ADWord, BDWord;
8352     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8353     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8354     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8355     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8356     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8357     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8358     int TripleNonInputIdx =
8359         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8360     TripleDWord = TripleNonInputIdx / 2;
8361
8362     // We use xor with one to compute the adjacent DWord to whichever one the
8363     // OneInput is in.
8364     OneInputDWord = (OneInput / 2) ^ 1;
8365
8366     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8367     // and BToA inputs. If there is also such a problem with the BToB and AToB
8368     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8369     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8370     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8371     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8372       // Compute how many inputs will be flipped by swapping these DWords. We
8373       // need
8374       // to balance this to ensure we don't form a 3-1 shuffle in the other
8375       // half.
8376       int NumFlippedAToBInputs =
8377           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8378           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8379       int NumFlippedBToBInputs =
8380           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8381           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8382       if ((NumFlippedAToBInputs == 1 &&
8383            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8384           (NumFlippedBToBInputs == 1 &&
8385            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8386         // We choose whether to fix the A half or B half based on whether that
8387         // half has zero flipped inputs. At zero, we may not be able to fix it
8388         // with that half. We also bias towards fixing the B half because that
8389         // will more commonly be the high half, and we have to bias one way.
8390         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8391                                                        ArrayRef<int> Inputs) {
8392           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8393           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8394                                          PinnedIdx ^ 1) != Inputs.end();
8395           // Determine whether the free index is in the flipped dword or the
8396           // unflipped dword based on where the pinned index is. We use this bit
8397           // in an xor to conditionally select the adjacent dword.
8398           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8399           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8400                                              FixFreeIdx) != Inputs.end();
8401           if (IsFixIdxInput == IsFixFreeIdxInput)
8402             FixFreeIdx += 1;
8403           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8404                                         FixFreeIdx) != Inputs.end();
8405           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8406                  "We need to be changing the number of flipped inputs!");
8407           int PSHUFHalfMask[] = {0, 1, 2, 3};
8408           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8409           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8410                           MVT::v8i16, V,
8411                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8412
8413           for (int &M : Mask)
8414             if (M != -1 && M == FixIdx)
8415               M = FixFreeIdx;
8416             else if (M != -1 && M == FixFreeIdx)
8417               M = FixIdx;
8418         };
8419         if (NumFlippedBToBInputs != 0) {
8420           int BPinnedIdx =
8421               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8422           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8423         } else {
8424           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8425           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8426           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8427         }
8428       }
8429     }
8430
8431     int PSHUFDMask[] = {0, 1, 2, 3};
8432     PSHUFDMask[ADWord] = BDWord;
8433     PSHUFDMask[BDWord] = ADWord;
8434     V = DAG.getBitcast(
8435         VT,
8436         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8437                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8438
8439     // Adjust the mask to match the new locations of A and B.
8440     for (int &M : Mask)
8441       if (M != -1 && M/2 == ADWord)
8442         M = 2 * BDWord + M % 2;
8443       else if (M != -1 && M/2 == BDWord)
8444         M = 2 * ADWord + M % 2;
8445
8446     // Recurse back into this routine to re-compute state now that this isn't
8447     // a 3 and 1 problem.
8448     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8449                                                      DAG);
8450   };
8451   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8452     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8453   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8454     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8455
8456   // At this point there are at most two inputs to the low and high halves from
8457   // each half. That means the inputs can always be grouped into dwords and
8458   // those dwords can then be moved to the correct half with a dword shuffle.
8459   // We use at most one low and one high word shuffle to collect these paired
8460   // inputs into dwords, and finally a dword shuffle to place them.
8461   int PSHUFLMask[4] = {-1, -1, -1, -1};
8462   int PSHUFHMask[4] = {-1, -1, -1, -1};
8463   int PSHUFDMask[4] = {-1, -1, -1, -1};
8464
8465   // First fix the masks for all the inputs that are staying in their
8466   // original halves. This will then dictate the targets of the cross-half
8467   // shuffles.
8468   auto fixInPlaceInputs =
8469       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8470                     MutableArrayRef<int> SourceHalfMask,
8471                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8472     if (InPlaceInputs.empty())
8473       return;
8474     if (InPlaceInputs.size() == 1) {
8475       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8476           InPlaceInputs[0] - HalfOffset;
8477       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8478       return;
8479     }
8480     if (IncomingInputs.empty()) {
8481       // Just fix all of the in place inputs.
8482       for (int Input : InPlaceInputs) {
8483         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8484         PSHUFDMask[Input / 2] = Input / 2;
8485       }
8486       return;
8487     }
8488
8489     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8490     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8491         InPlaceInputs[0] - HalfOffset;
8492     // Put the second input next to the first so that they are packed into
8493     // a dword. We find the adjacent index by toggling the low bit.
8494     int AdjIndex = InPlaceInputs[0] ^ 1;
8495     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8496     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8497     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8498   };
8499   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8500   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8501
8502   // Now gather the cross-half inputs and place them into a free dword of
8503   // their target half.
8504   // FIXME: This operation could almost certainly be simplified dramatically to
8505   // look more like the 3-1 fixing operation.
8506   auto moveInputsToRightHalf = [&PSHUFDMask](
8507       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8508       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8509       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8510       int DestOffset) {
8511     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8512       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8513     };
8514     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8515                                                int Word) {
8516       int LowWord = Word & ~1;
8517       int HighWord = Word | 1;
8518       return isWordClobbered(SourceHalfMask, LowWord) ||
8519              isWordClobbered(SourceHalfMask, HighWord);
8520     };
8521
8522     if (IncomingInputs.empty())
8523       return;
8524
8525     if (ExistingInputs.empty()) {
8526       // Map any dwords with inputs from them into the right half.
8527       for (int Input : IncomingInputs) {
8528         // If the source half mask maps over the inputs, turn those into
8529         // swaps and use the swapped lane.
8530         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8531           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8532             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8533                 Input - SourceOffset;
8534             // We have to swap the uses in our half mask in one sweep.
8535             for (int &M : HalfMask)
8536               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8537                 M = Input;
8538               else if (M == Input)
8539                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8540           } else {
8541             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8542                        Input - SourceOffset &&
8543                    "Previous placement doesn't match!");
8544           }
8545           // Note that this correctly re-maps both when we do a swap and when
8546           // we observe the other side of the swap above. We rely on that to
8547           // avoid swapping the members of the input list directly.
8548           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8549         }
8550
8551         // Map the input's dword into the correct half.
8552         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8553           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8554         else
8555           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8556                      Input / 2 &&
8557                  "Previous placement doesn't match!");
8558       }
8559
8560       // And just directly shift any other-half mask elements to be same-half
8561       // as we will have mirrored the dword containing the element into the
8562       // same position within that half.
8563       for (int &M : HalfMask)
8564         if (M >= SourceOffset && M < SourceOffset + 4) {
8565           M = M - SourceOffset + DestOffset;
8566           assert(M >= 0 && "This should never wrap below zero!");
8567         }
8568       return;
8569     }
8570
8571     // Ensure we have the input in a viable dword of its current half. This
8572     // is particularly tricky because the original position may be clobbered
8573     // by inputs being moved and *staying* in that half.
8574     if (IncomingInputs.size() == 1) {
8575       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8576         int InputFixed = std::find(std::begin(SourceHalfMask),
8577                                    std::end(SourceHalfMask), -1) -
8578                          std::begin(SourceHalfMask) + SourceOffset;
8579         SourceHalfMask[InputFixed - SourceOffset] =
8580             IncomingInputs[0] - SourceOffset;
8581         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8582                      InputFixed);
8583         IncomingInputs[0] = InputFixed;
8584       }
8585     } else if (IncomingInputs.size() == 2) {
8586       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8587           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8588         // We have two non-adjacent or clobbered inputs we need to extract from
8589         // the source half. To do this, we need to map them into some adjacent
8590         // dword slot in the source mask.
8591         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8592                               IncomingInputs[1] - SourceOffset};
8593
8594         // If there is a free slot in the source half mask adjacent to one of
8595         // the inputs, place the other input in it. We use (Index XOR 1) to
8596         // compute an adjacent index.
8597         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8598             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8599           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8600           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8601           InputsFixed[1] = InputsFixed[0] ^ 1;
8602         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8603                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8604           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8605           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8606           InputsFixed[0] = InputsFixed[1] ^ 1;
8607         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8608                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8609           // The two inputs are in the same DWord but it is clobbered and the
8610           // adjacent DWord isn't used at all. Move both inputs to the free
8611           // slot.
8612           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8613           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8614           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8615           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8616         } else {
8617           // The only way we hit this point is if there is no clobbering
8618           // (because there are no off-half inputs to this half) and there is no
8619           // free slot adjacent to one of the inputs. In this case, we have to
8620           // swap an input with a non-input.
8621           for (int i = 0; i < 4; ++i)
8622             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8623                    "We can't handle any clobbers here!");
8624           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8625                  "Cannot have adjacent inputs here!");
8626
8627           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8628           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8629
8630           // We also have to update the final source mask in this case because
8631           // it may need to undo the above swap.
8632           for (int &M : FinalSourceHalfMask)
8633             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8634               M = InputsFixed[1] + SourceOffset;
8635             else if (M == InputsFixed[1] + SourceOffset)
8636               M = (InputsFixed[0] ^ 1) + SourceOffset;
8637
8638           InputsFixed[1] = InputsFixed[0] ^ 1;
8639         }
8640
8641         // Point everything at the fixed inputs.
8642         for (int &M : HalfMask)
8643           if (M == IncomingInputs[0])
8644             M = InputsFixed[0] + SourceOffset;
8645           else if (M == IncomingInputs[1])
8646             M = InputsFixed[1] + SourceOffset;
8647
8648         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8649         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8650       }
8651     } else {
8652       llvm_unreachable("Unhandled input size!");
8653     }
8654
8655     // Now hoist the DWord down to the right half.
8656     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8657     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8658     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8659     for (int &M : HalfMask)
8660       for (int Input : IncomingInputs)
8661         if (M == Input)
8662           M = FreeDWord * 2 + Input % 2;
8663   };
8664   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8665                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8666   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8667                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8668
8669   // Now enact all the shuffles we've computed to move the inputs into their
8670   // target half.
8671   if (!isNoopShuffleMask(PSHUFLMask))
8672     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8673                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8674   if (!isNoopShuffleMask(PSHUFHMask))
8675     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8676                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8677   if (!isNoopShuffleMask(PSHUFDMask))
8678     V = DAG.getBitcast(
8679         VT,
8680         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8681                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8682
8683   // At this point, each half should contain all its inputs, and we can then
8684   // just shuffle them into their final position.
8685   assert(std::count_if(LoMask.begin(), LoMask.end(),
8686                        [](int M) { return M >= 4; }) == 0 &&
8687          "Failed to lift all the high half inputs to the low mask!");
8688   assert(std::count_if(HiMask.begin(), HiMask.end(),
8689                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8690          "Failed to lift all the low half inputs to the high mask!");
8691
8692   // Do a half shuffle for the low mask.
8693   if (!isNoopShuffleMask(LoMask))
8694     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8695                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8696
8697   // Do a half shuffle with the high mask after shifting its values down.
8698   for (int &M : HiMask)
8699     if (M >= 0)
8700       M -= 4;
8701   if (!isNoopShuffleMask(HiMask))
8702     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8703                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8704
8705   return V;
8706 }
8707
8708 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8709 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8710                                           SDValue V2, ArrayRef<int> Mask,
8711                                           SelectionDAG &DAG, bool &V1InUse,
8712                                           bool &V2InUse) {
8713   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8714   SDValue V1Mask[16];
8715   SDValue V2Mask[16];
8716   V1InUse = false;
8717   V2InUse = false;
8718
8719   int Size = Mask.size();
8720   int Scale = 16 / Size;
8721   for (int i = 0; i < 16; ++i) {
8722     if (Mask[i / Scale] == -1) {
8723       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8724     } else {
8725       const int ZeroMask = 0x80;
8726       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8727                                           : ZeroMask;
8728       int V2Idx = Mask[i / Scale] < Size
8729                       ? ZeroMask
8730                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8731       if (Zeroable[i / Scale])
8732         V1Idx = V2Idx = ZeroMask;
8733       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8734       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8735       V1InUse |= (ZeroMask != V1Idx);
8736       V2InUse |= (ZeroMask != V2Idx);
8737     }
8738   }
8739
8740   if (V1InUse)
8741     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8742                      DAG.getBitcast(MVT::v16i8, V1),
8743                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8744   if (V2InUse)
8745     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8746                      DAG.getBitcast(MVT::v16i8, V2),
8747                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8748
8749   // If we need shuffled inputs from both, blend the two.
8750   SDValue V;
8751   if (V1InUse && V2InUse)
8752     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8753   else
8754     V = V1InUse ? V1 : V2;
8755
8756   // Cast the result back to the correct type.
8757   return DAG.getBitcast(VT, V);
8758 }
8759
8760 /// \brief Generic lowering of 8-lane i16 shuffles.
8761 ///
8762 /// This handles both single-input shuffles and combined shuffle/blends with
8763 /// two inputs. The single input shuffles are immediately delegated to
8764 /// a dedicated lowering routine.
8765 ///
8766 /// The blends are lowered in one of three fundamental ways. If there are few
8767 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8768 /// of the input is significantly cheaper when lowered as an interleaving of
8769 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8770 /// halves of the inputs separately (making them have relatively few inputs)
8771 /// and then concatenate them.
8772 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8773                                        const X86Subtarget *Subtarget,
8774                                        SelectionDAG &DAG) {
8775   SDLoc DL(Op);
8776   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8777   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8778   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8779   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8780   ArrayRef<int> OrigMask = SVOp->getMask();
8781   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8782                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8783   MutableArrayRef<int> Mask(MaskStorage);
8784
8785   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8786
8787   // Whenever we can lower this as a zext, that instruction is strictly faster
8788   // than any alternative.
8789   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8790           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8791     return ZExt;
8792
8793   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8794   (void)isV1;
8795   auto isV2 = [](int M) { return M >= 8; };
8796
8797   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8798
8799   if (NumV2Inputs == 0) {
8800     // Check for being able to broadcast a single element.
8801     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8802                                                           Mask, Subtarget, DAG))
8803       return Broadcast;
8804
8805     // Try to use shift instructions.
8806     if (SDValue Shift =
8807             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8808       return Shift;
8809
8810     // Use dedicated unpack instructions for masks that match their pattern.
8811     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8812       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8813     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8814       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8815
8816     // Try to use byte rotation instructions.
8817     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8818                                                         Mask, Subtarget, DAG))
8819       return Rotate;
8820
8821     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8822                                                      Subtarget, DAG);
8823   }
8824
8825   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8826          "All single-input shuffles should be canonicalized to be V1-input "
8827          "shuffles.");
8828
8829   // Try to use shift instructions.
8830   if (SDValue Shift =
8831           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8832     return Shift;
8833
8834   // See if we can use SSE4A Extraction / Insertion.
8835   if (Subtarget->hasSSE4A())
8836     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8837       return V;
8838
8839   // There are special ways we can lower some single-element blends.
8840   if (NumV2Inputs == 1)
8841     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8842                                                          Mask, Subtarget, DAG))
8843       return V;
8844
8845   // We have different paths for blend lowering, but they all must use the
8846   // *exact* same predicate.
8847   bool IsBlendSupported = Subtarget->hasSSE41();
8848   if (IsBlendSupported)
8849     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8850                                                   Subtarget, DAG))
8851       return Blend;
8852
8853   if (SDValue Masked =
8854           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8855     return Masked;
8856
8857   // Use dedicated unpack instructions for masks that match their pattern.
8858   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8859     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8860   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8861     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8862
8863   // Try to use byte rotation instructions.
8864   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8865           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8866     return Rotate;
8867
8868   if (SDValue BitBlend =
8869           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8870     return BitBlend;
8871
8872   if (SDValue Unpack =
8873           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8874     return Unpack;
8875
8876   // If we can't directly blend but can use PSHUFB, that will be better as it
8877   // can both shuffle and set up the inefficient blend.
8878   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8879     bool V1InUse, V2InUse;
8880     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8881                                       V1InUse, V2InUse);
8882   }
8883
8884   // We can always bit-blend if we have to so the fallback strategy is to
8885   // decompose into single-input permutes and blends.
8886   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8887                                                       Mask, DAG);
8888 }
8889
8890 /// \brief Check whether a compaction lowering can be done by dropping even
8891 /// elements and compute how many times even elements must be dropped.
8892 ///
8893 /// This handles shuffles which take every Nth element where N is a power of
8894 /// two. Example shuffle masks:
8895 ///
8896 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8897 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8898 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8899 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8900 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8901 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8902 ///
8903 /// Any of these lanes can of course be undef.
8904 ///
8905 /// This routine only supports N <= 3.
8906 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8907 /// for larger N.
8908 ///
8909 /// \returns N above, or the number of times even elements must be dropped if
8910 /// there is such a number. Otherwise returns zero.
8911 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8912   // Figure out whether we're looping over two inputs or just one.
8913   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8914
8915   // The modulus for the shuffle vector entries is based on whether this is
8916   // a single input or not.
8917   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8918   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8919          "We should only be called with masks with a power-of-2 size!");
8920
8921   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8922
8923   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8924   // and 2^3 simultaneously. This is because we may have ambiguity with
8925   // partially undef inputs.
8926   bool ViableForN[3] = {true, true, true};
8927
8928   for (int i = 0, e = Mask.size(); i < e; ++i) {
8929     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8930     // want.
8931     if (Mask[i] == -1)
8932       continue;
8933
8934     bool IsAnyViable = false;
8935     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8936       if (ViableForN[j]) {
8937         uint64_t N = j + 1;
8938
8939         // The shuffle mask must be equal to (i * 2^N) % M.
8940         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8941           IsAnyViable = true;
8942         else
8943           ViableForN[j] = false;
8944       }
8945     // Early exit if we exhaust the possible powers of two.
8946     if (!IsAnyViable)
8947       break;
8948   }
8949
8950   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8951     if (ViableForN[j])
8952       return j + 1;
8953
8954   // Return 0 as there is no viable power of two.
8955   return 0;
8956 }
8957
8958 /// \brief Generic lowering of v16i8 shuffles.
8959 ///
8960 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8961 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8962 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8963 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8964 /// back together.
8965 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8966                                        const X86Subtarget *Subtarget,
8967                                        SelectionDAG &DAG) {
8968   SDLoc DL(Op);
8969   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8970   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8971   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8972   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8973   ArrayRef<int> Mask = SVOp->getMask();
8974   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8975
8976   // Try to use shift instructions.
8977   if (SDValue Shift =
8978           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8979     return Shift;
8980
8981   // Try to use byte rotation instructions.
8982   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8983           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8984     return Rotate;
8985
8986   // Try to use a zext lowering.
8987   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8988           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8989     return ZExt;
8990
8991   // See if we can use SSE4A Extraction / Insertion.
8992   if (Subtarget->hasSSE4A())
8993     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8994       return V;
8995
8996   int NumV2Elements =
8997       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8998
8999   // For single-input shuffles, there are some nicer lowering tricks we can use.
9000   if (NumV2Elements == 0) {
9001     // Check for being able to broadcast a single element.
9002     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9003                                                           Mask, Subtarget, DAG))
9004       return Broadcast;
9005
9006     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9007     // Notably, this handles splat and partial-splat shuffles more efficiently.
9008     // However, it only makes sense if the pre-duplication shuffle simplifies
9009     // things significantly. Currently, this means we need to be able to
9010     // express the pre-duplication shuffle as an i16 shuffle.
9011     //
9012     // FIXME: We should check for other patterns which can be widened into an
9013     // i16 shuffle as well.
9014     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9015       for (int i = 0; i < 16; i += 2)
9016         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9017           return false;
9018
9019       return true;
9020     };
9021     auto tryToWidenViaDuplication = [&]() -> SDValue {
9022       if (!canWidenViaDuplication(Mask))
9023         return SDValue();
9024       SmallVector<int, 4> LoInputs;
9025       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9026                    [](int M) { return M >= 0 && M < 8; });
9027       std::sort(LoInputs.begin(), LoInputs.end());
9028       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9029                      LoInputs.end());
9030       SmallVector<int, 4> HiInputs;
9031       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9032                    [](int M) { return M >= 8; });
9033       std::sort(HiInputs.begin(), HiInputs.end());
9034       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9035                      HiInputs.end());
9036
9037       bool TargetLo = LoInputs.size() >= HiInputs.size();
9038       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9039       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9040
9041       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9042       SmallDenseMap<int, int, 8> LaneMap;
9043       for (int I : InPlaceInputs) {
9044         PreDupI16Shuffle[I/2] = I/2;
9045         LaneMap[I] = I;
9046       }
9047       int j = TargetLo ? 0 : 4, je = j + 4;
9048       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9049         // Check if j is already a shuffle of this input. This happens when
9050         // there are two adjacent bytes after we move the low one.
9051         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9052           // If we haven't yet mapped the input, search for a slot into which
9053           // we can map it.
9054           while (j < je && PreDupI16Shuffle[j] != -1)
9055             ++j;
9056
9057           if (j == je)
9058             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9059             return SDValue();
9060
9061           // Map this input with the i16 shuffle.
9062           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9063         }
9064
9065         // Update the lane map based on the mapping we ended up with.
9066         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9067       }
9068       V1 = DAG.getBitcast(
9069           MVT::v16i8,
9070           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9071                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9072
9073       // Unpack the bytes to form the i16s that will be shuffled into place.
9074       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9075                        MVT::v16i8, V1, V1);
9076
9077       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9078       for (int i = 0; i < 16; ++i)
9079         if (Mask[i] != -1) {
9080           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9081           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9082           if (PostDupI16Shuffle[i / 2] == -1)
9083             PostDupI16Shuffle[i / 2] = MappedMask;
9084           else
9085             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9086                    "Conflicting entrties in the original shuffle!");
9087         }
9088       return DAG.getBitcast(
9089           MVT::v16i8,
9090           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9091                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9092     };
9093     if (SDValue V = tryToWidenViaDuplication())
9094       return V;
9095   }
9096
9097   if (SDValue Masked =
9098           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9099     return Masked;
9100
9101   // Use dedicated unpack instructions for masks that match their pattern.
9102   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9103                                          0, 16, 1, 17, 2, 18, 3, 19,
9104                                          // High half.
9105                                          4, 20, 5, 21, 6, 22, 7, 23}))
9106     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9107   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9108                                          8, 24, 9, 25, 10, 26, 11, 27,
9109                                          // High half.
9110                                          12, 28, 13, 29, 14, 30, 15, 31}))
9111     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9112
9113   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9114   // with PSHUFB. It is important to do this before we attempt to generate any
9115   // blends but after all of the single-input lowerings. If the single input
9116   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9117   // want to preserve that and we can DAG combine any longer sequences into
9118   // a PSHUFB in the end. But once we start blending from multiple inputs,
9119   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9120   // and there are *very* few patterns that would actually be faster than the
9121   // PSHUFB approach because of its ability to zero lanes.
9122   //
9123   // FIXME: The only exceptions to the above are blends which are exact
9124   // interleavings with direct instructions supporting them. We currently don't
9125   // handle those well here.
9126   if (Subtarget->hasSSSE3()) {
9127     bool V1InUse = false;
9128     bool V2InUse = false;
9129
9130     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9131                                                 DAG, V1InUse, V2InUse);
9132
9133     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9134     // do so. This avoids using them to handle blends-with-zero which is
9135     // important as a single pshufb is significantly faster for that.
9136     if (V1InUse && V2InUse) {
9137       if (Subtarget->hasSSE41())
9138         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9139                                                       Mask, Subtarget, DAG))
9140           return Blend;
9141
9142       // We can use an unpack to do the blending rather than an or in some
9143       // cases. Even though the or may be (very minorly) more efficient, we
9144       // preference this lowering because there are common cases where part of
9145       // the complexity of the shuffles goes away when we do the final blend as
9146       // an unpack.
9147       // FIXME: It might be worth trying to detect if the unpack-feeding
9148       // shuffles will both be pshufb, in which case we shouldn't bother with
9149       // this.
9150       if (SDValue Unpack =
9151               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9152         return Unpack;
9153     }
9154
9155     return PSHUFB;
9156   }
9157
9158   // There are special ways we can lower some single-element blends.
9159   if (NumV2Elements == 1)
9160     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9161                                                          Mask, Subtarget, DAG))
9162       return V;
9163
9164   if (SDValue BitBlend =
9165           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9166     return BitBlend;
9167
9168   // Check whether a compaction lowering can be done. This handles shuffles
9169   // which take every Nth element for some even N. See the helper function for
9170   // details.
9171   //
9172   // We special case these as they can be particularly efficiently handled with
9173   // the PACKUSB instruction on x86 and they show up in common patterns of
9174   // rearranging bytes to truncate wide elements.
9175   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9176     // NumEvenDrops is the power of two stride of the elements. Another way of
9177     // thinking about it is that we need to drop the even elements this many
9178     // times to get the original input.
9179     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9180
9181     // First we need to zero all the dropped bytes.
9182     assert(NumEvenDrops <= 3 &&
9183            "No support for dropping even elements more than 3 times.");
9184     // We use the mask type to pick which bytes are preserved based on how many
9185     // elements are dropped.
9186     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9187     SDValue ByteClearMask = DAG.getBitcast(
9188         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9189     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9190     if (!IsSingleInput)
9191       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9192
9193     // Now pack things back together.
9194     V1 = DAG.getBitcast(MVT::v8i16, V1);
9195     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9196     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9197     for (int i = 1; i < NumEvenDrops; ++i) {
9198       Result = DAG.getBitcast(MVT::v8i16, Result);
9199       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9200     }
9201
9202     return Result;
9203   }
9204
9205   // Handle multi-input cases by blending single-input shuffles.
9206   if (NumV2Elements > 0)
9207     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9208                                                       Mask, DAG);
9209
9210   // The fallback path for single-input shuffles widens this into two v8i16
9211   // vectors with unpacks, shuffles those, and then pulls them back together
9212   // with a pack.
9213   SDValue V = V1;
9214
9215   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9216   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9217   for (int i = 0; i < 16; ++i)
9218     if (Mask[i] >= 0)
9219       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9220
9221   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9222
9223   SDValue VLoHalf, VHiHalf;
9224   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9225   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9226   // i16s.
9227   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9228                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9229       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9230                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9231     // Use a mask to drop the high bytes.
9232     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9233     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9234                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9235
9236     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9237     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9238
9239     // Squash the masks to point directly into VLoHalf.
9240     for (int &M : LoBlendMask)
9241       if (M >= 0)
9242         M /= 2;
9243     for (int &M : HiBlendMask)
9244       if (M >= 0)
9245         M /= 2;
9246   } else {
9247     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9248     // VHiHalf so that we can blend them as i16s.
9249     VLoHalf = DAG.getBitcast(
9250         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9251     VHiHalf = DAG.getBitcast(
9252         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9253   }
9254
9255   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9256   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9257
9258   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9259 }
9260
9261 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9262 ///
9263 /// This routine breaks down the specific type of 128-bit shuffle and
9264 /// dispatches to the lowering routines accordingly.
9265 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9266                                         MVT VT, const X86Subtarget *Subtarget,
9267                                         SelectionDAG &DAG) {
9268   switch (VT.SimpleTy) {
9269   case MVT::v2i64:
9270     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9271   case MVT::v2f64:
9272     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9273   case MVT::v4i32:
9274     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9275   case MVT::v4f32:
9276     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9277   case MVT::v8i16:
9278     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9279   case MVT::v16i8:
9280     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9281
9282   default:
9283     llvm_unreachable("Unimplemented!");
9284   }
9285 }
9286
9287 /// \brief Helper function to test whether a shuffle mask could be
9288 /// simplified by widening the elements being shuffled.
9289 ///
9290 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9291 /// leaves it in an unspecified state.
9292 ///
9293 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9294 /// shuffle masks. The latter have the special property of a '-2' representing
9295 /// a zero-ed lane of a vector.
9296 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9297                                     SmallVectorImpl<int> &WidenedMask) {
9298   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9299     // If both elements are undef, its trivial.
9300     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9301       WidenedMask.push_back(SM_SentinelUndef);
9302       continue;
9303     }
9304
9305     // Check for an undef mask and a mask value properly aligned to fit with
9306     // a pair of values. If we find such a case, use the non-undef mask's value.
9307     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9308       WidenedMask.push_back(Mask[i + 1] / 2);
9309       continue;
9310     }
9311     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9312       WidenedMask.push_back(Mask[i] / 2);
9313       continue;
9314     }
9315
9316     // When zeroing, we need to spread the zeroing across both lanes to widen.
9317     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9318       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9319           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9320         WidenedMask.push_back(SM_SentinelZero);
9321         continue;
9322       }
9323       return false;
9324     }
9325
9326     // Finally check if the two mask values are adjacent and aligned with
9327     // a pair.
9328     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9329       WidenedMask.push_back(Mask[i] / 2);
9330       continue;
9331     }
9332
9333     // Otherwise we can't safely widen the elements used in this shuffle.
9334     return false;
9335   }
9336   assert(WidenedMask.size() == Mask.size() / 2 &&
9337          "Incorrect size of mask after widening the elements!");
9338
9339   return true;
9340 }
9341
9342 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9343 ///
9344 /// This routine just extracts two subvectors, shuffles them independently, and
9345 /// then concatenates them back together. This should work effectively with all
9346 /// AVX vector shuffle types.
9347 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9348                                           SDValue V2, ArrayRef<int> Mask,
9349                                           SelectionDAG &DAG) {
9350   assert(VT.getSizeInBits() >= 256 &&
9351          "Only for 256-bit or wider vector shuffles!");
9352   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9353   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9354
9355   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9356   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9357
9358   int NumElements = VT.getVectorNumElements();
9359   int SplitNumElements = NumElements / 2;
9360   MVT ScalarVT = VT.getScalarType();
9361   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9362
9363   // Rather than splitting build-vectors, just build two narrower build
9364   // vectors. This helps shuffling with splats and zeros.
9365   auto SplitVector = [&](SDValue V) {
9366     while (V.getOpcode() == ISD::BITCAST)
9367       V = V->getOperand(0);
9368
9369     MVT OrigVT = V.getSimpleValueType();
9370     int OrigNumElements = OrigVT.getVectorNumElements();
9371     int OrigSplitNumElements = OrigNumElements / 2;
9372     MVT OrigScalarVT = OrigVT.getScalarType();
9373     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9374
9375     SDValue LoV, HiV;
9376
9377     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9378     if (!BV) {
9379       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9380                         DAG.getIntPtrConstant(0, DL));
9381       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9382                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9383     } else {
9384
9385       SmallVector<SDValue, 16> LoOps, HiOps;
9386       for (int i = 0; i < OrigSplitNumElements; ++i) {
9387         LoOps.push_back(BV->getOperand(i));
9388         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9389       }
9390       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9391       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9392     }
9393     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9394                           DAG.getBitcast(SplitVT, HiV));
9395   };
9396
9397   SDValue LoV1, HiV1, LoV2, HiV2;
9398   std::tie(LoV1, HiV1) = SplitVector(V1);
9399   std::tie(LoV2, HiV2) = SplitVector(V2);
9400
9401   // Now create two 4-way blends of these half-width vectors.
9402   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9403     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9404     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9405     for (int i = 0; i < SplitNumElements; ++i) {
9406       int M = HalfMask[i];
9407       if (M >= NumElements) {
9408         if (M >= NumElements + SplitNumElements)
9409           UseHiV2 = true;
9410         else
9411           UseLoV2 = true;
9412         V2BlendMask.push_back(M - NumElements);
9413         V1BlendMask.push_back(-1);
9414         BlendMask.push_back(SplitNumElements + i);
9415       } else if (M >= 0) {
9416         if (M >= SplitNumElements)
9417           UseHiV1 = true;
9418         else
9419           UseLoV1 = true;
9420         V2BlendMask.push_back(-1);
9421         V1BlendMask.push_back(M);
9422         BlendMask.push_back(i);
9423       } else {
9424         V2BlendMask.push_back(-1);
9425         V1BlendMask.push_back(-1);
9426         BlendMask.push_back(-1);
9427       }
9428     }
9429
9430     // Because the lowering happens after all combining takes place, we need to
9431     // manually combine these blend masks as much as possible so that we create
9432     // a minimal number of high-level vector shuffle nodes.
9433
9434     // First try just blending the halves of V1 or V2.
9435     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9436       return DAG.getUNDEF(SplitVT);
9437     if (!UseLoV2 && !UseHiV2)
9438       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9439     if (!UseLoV1 && !UseHiV1)
9440       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9441
9442     SDValue V1Blend, V2Blend;
9443     if (UseLoV1 && UseHiV1) {
9444       V1Blend =
9445         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9446     } else {
9447       // We only use half of V1 so map the usage down into the final blend mask.
9448       V1Blend = UseLoV1 ? LoV1 : HiV1;
9449       for (int i = 0; i < SplitNumElements; ++i)
9450         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9451           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9452     }
9453     if (UseLoV2 && UseHiV2) {
9454       V2Blend =
9455         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9456     } else {
9457       // We only use half of V2 so map the usage down into the final blend mask.
9458       V2Blend = UseLoV2 ? LoV2 : HiV2;
9459       for (int i = 0; i < SplitNumElements; ++i)
9460         if (BlendMask[i] >= SplitNumElements)
9461           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9462     }
9463     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9464   };
9465   SDValue Lo = HalfBlend(LoMask);
9466   SDValue Hi = HalfBlend(HiMask);
9467   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9468 }
9469
9470 /// \brief Either split a vector in halves or decompose the shuffles and the
9471 /// blend.
9472 ///
9473 /// This is provided as a good fallback for many lowerings of non-single-input
9474 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9475 /// between splitting the shuffle into 128-bit components and stitching those
9476 /// back together vs. extracting the single-input shuffles and blending those
9477 /// results.
9478 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9479                                                 SDValue V2, ArrayRef<int> Mask,
9480                                                 SelectionDAG &DAG) {
9481   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9482                                             "lower single-input shuffles as it "
9483                                             "could then recurse on itself.");
9484   int Size = Mask.size();
9485
9486   // If this can be modeled as a broadcast of two elements followed by a blend,
9487   // prefer that lowering. This is especially important because broadcasts can
9488   // often fold with memory operands.
9489   auto DoBothBroadcast = [&] {
9490     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9491     for (int M : Mask)
9492       if (M >= Size) {
9493         if (V2BroadcastIdx == -1)
9494           V2BroadcastIdx = M - Size;
9495         else if (M - Size != V2BroadcastIdx)
9496           return false;
9497       } else if (M >= 0) {
9498         if (V1BroadcastIdx == -1)
9499           V1BroadcastIdx = M;
9500         else if (M != V1BroadcastIdx)
9501           return false;
9502       }
9503     return true;
9504   };
9505   if (DoBothBroadcast())
9506     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9507                                                       DAG);
9508
9509   // If the inputs all stem from a single 128-bit lane of each input, then we
9510   // split them rather than blending because the split will decompose to
9511   // unusually few instructions.
9512   int LaneCount = VT.getSizeInBits() / 128;
9513   int LaneSize = Size / LaneCount;
9514   SmallBitVector LaneInputs[2];
9515   LaneInputs[0].resize(LaneCount, false);
9516   LaneInputs[1].resize(LaneCount, false);
9517   for (int i = 0; i < Size; ++i)
9518     if (Mask[i] >= 0)
9519       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9520   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9521     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9522
9523   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9524   // that the decomposed single-input shuffles don't end up here.
9525   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9526 }
9527
9528 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9529 /// a permutation and blend of those lanes.
9530 ///
9531 /// This essentially blends the out-of-lane inputs to each lane into the lane
9532 /// from a permuted copy of the vector. This lowering strategy results in four
9533 /// instructions in the worst case for a single-input cross lane shuffle which
9534 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9535 /// of. Special cases for each particular shuffle pattern should be handled
9536 /// prior to trying this lowering.
9537 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9538                                                        SDValue V1, SDValue V2,
9539                                                        ArrayRef<int> Mask,
9540                                                        SelectionDAG &DAG) {
9541   // FIXME: This should probably be generalized for 512-bit vectors as well.
9542   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9543   int LaneSize = Mask.size() / 2;
9544
9545   // If there are only inputs from one 128-bit lane, splitting will in fact be
9546   // less expensive. The flags track whether the given lane contains an element
9547   // that crosses to another lane.
9548   bool LaneCrossing[2] = {false, false};
9549   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9550     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9551       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9552   if (!LaneCrossing[0] || !LaneCrossing[1])
9553     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9554
9555   if (isSingleInputShuffleMask(Mask)) {
9556     SmallVector<int, 32> FlippedBlendMask;
9557     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9558       FlippedBlendMask.push_back(
9559           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9560                                   ? Mask[i]
9561                                   : Mask[i] % LaneSize +
9562                                         (i / LaneSize) * LaneSize + Size));
9563
9564     // Flip the vector, and blend the results which should now be in-lane. The
9565     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9566     // 5 for the high source. The value 3 selects the high half of source 2 and
9567     // the value 2 selects the low half of source 2. We only use source 2 to
9568     // allow folding it into a memory operand.
9569     unsigned PERMMask = 3 | 2 << 4;
9570     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9571                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9572     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9573   }
9574
9575   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9576   // will be handled by the above logic and a blend of the results, much like
9577   // other patterns in AVX.
9578   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9579 }
9580
9581 /// \brief Handle lowering 2-lane 128-bit shuffles.
9582 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9583                                         SDValue V2, ArrayRef<int> Mask,
9584                                         const X86Subtarget *Subtarget,
9585                                         SelectionDAG &DAG) {
9586   // TODO: If minimizing size and one of the inputs is a zero vector and the
9587   // the zero vector has only one use, we could use a VPERM2X128 to save the
9588   // instruction bytes needed to explicitly generate the zero vector.
9589
9590   // Blends are faster and handle all the non-lane-crossing cases.
9591   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9592                                                 Subtarget, DAG))
9593     return Blend;
9594
9595   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9596   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9597
9598   // If either input operand is a zero vector, use VPERM2X128 because its mask
9599   // allows us to replace the zero input with an implicit zero.
9600   if (!IsV1Zero && !IsV2Zero) {
9601     // Check for patterns which can be matched with a single insert of a 128-bit
9602     // subvector.
9603     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9604     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9605       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9606                                    VT.getVectorNumElements() / 2);
9607       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9608                                 DAG.getIntPtrConstant(0, DL));
9609       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9610                                 OnlyUsesV1 ? V1 : V2,
9611                                 DAG.getIntPtrConstant(0, DL));
9612       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9613     }
9614   }
9615
9616   // Otherwise form a 128-bit permutation. After accounting for undefs,
9617   // convert the 64-bit shuffle mask selection values into 128-bit
9618   // selection bits by dividing the indexes by 2 and shifting into positions
9619   // defined by a vperm2*128 instruction's immediate control byte.
9620
9621   // The immediate permute control byte looks like this:
9622   //    [1:0] - select 128 bits from sources for low half of destination
9623   //    [2]   - ignore
9624   //    [3]   - zero low half of destination
9625   //    [5:4] - select 128 bits from sources for high half of destination
9626   //    [6]   - ignore
9627   //    [7]   - zero high half of destination
9628
9629   int MaskLO = Mask[0];
9630   if (MaskLO == SM_SentinelUndef)
9631     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9632
9633   int MaskHI = Mask[2];
9634   if (MaskHI == SM_SentinelUndef)
9635     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9636
9637   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9638
9639   // If either input is a zero vector, replace it with an undef input.
9640   // Shuffle mask values <  4 are selecting elements of V1.
9641   // Shuffle mask values >= 4 are selecting elements of V2.
9642   // Adjust each half of the permute mask by clearing the half that was
9643   // selecting the zero vector and setting the zero mask bit.
9644   if (IsV1Zero) {
9645     V1 = DAG.getUNDEF(VT);
9646     if (MaskLO < 4)
9647       PermMask = (PermMask & 0xf0) | 0x08;
9648     if (MaskHI < 4)
9649       PermMask = (PermMask & 0x0f) | 0x80;
9650   }
9651   if (IsV2Zero) {
9652     V2 = DAG.getUNDEF(VT);
9653     if (MaskLO >= 4)
9654       PermMask = (PermMask & 0xf0) | 0x08;
9655     if (MaskHI >= 4)
9656       PermMask = (PermMask & 0x0f) | 0x80;
9657   }
9658
9659   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9660                      DAG.getConstant(PermMask, DL, MVT::i8));
9661 }
9662
9663 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9664 /// shuffling each lane.
9665 ///
9666 /// This will only succeed when the result of fixing the 128-bit lanes results
9667 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9668 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9669 /// the lane crosses early and then use simpler shuffles within each lane.
9670 ///
9671 /// FIXME: It might be worthwhile at some point to support this without
9672 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9673 /// in x86 only floating point has interesting non-repeating shuffles, and even
9674 /// those are still *marginally* more expensive.
9675 static SDValue lowerVectorShuffleByMerging128BitLanes(
9676     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9677     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9678   assert(!isSingleInputShuffleMask(Mask) &&
9679          "This is only useful with multiple inputs.");
9680
9681   int Size = Mask.size();
9682   int LaneSize = 128 / VT.getScalarSizeInBits();
9683   int NumLanes = Size / LaneSize;
9684   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9685
9686   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9687   // check whether the in-128-bit lane shuffles share a repeating pattern.
9688   SmallVector<int, 4> Lanes;
9689   Lanes.resize(NumLanes, -1);
9690   SmallVector<int, 4> InLaneMask;
9691   InLaneMask.resize(LaneSize, -1);
9692   for (int i = 0; i < Size; ++i) {
9693     if (Mask[i] < 0)
9694       continue;
9695
9696     int j = i / LaneSize;
9697
9698     if (Lanes[j] < 0) {
9699       // First entry we've seen for this lane.
9700       Lanes[j] = Mask[i] / LaneSize;
9701     } else if (Lanes[j] != Mask[i] / LaneSize) {
9702       // This doesn't match the lane selected previously!
9703       return SDValue();
9704     }
9705
9706     // Check that within each lane we have a consistent shuffle mask.
9707     int k = i % LaneSize;
9708     if (InLaneMask[k] < 0) {
9709       InLaneMask[k] = Mask[i] % LaneSize;
9710     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9711       // This doesn't fit a repeating in-lane mask.
9712       return SDValue();
9713     }
9714   }
9715
9716   // First shuffle the lanes into place.
9717   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9718                                 VT.getSizeInBits() / 64);
9719   SmallVector<int, 8> LaneMask;
9720   LaneMask.resize(NumLanes * 2, -1);
9721   for (int i = 0; i < NumLanes; ++i)
9722     if (Lanes[i] >= 0) {
9723       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9724       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9725     }
9726
9727   V1 = DAG.getBitcast(LaneVT, V1);
9728   V2 = DAG.getBitcast(LaneVT, V2);
9729   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9730
9731   // Cast it back to the type we actually want.
9732   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9733
9734   // Now do a simple shuffle that isn't lane crossing.
9735   SmallVector<int, 8> NewMask;
9736   NewMask.resize(Size, -1);
9737   for (int i = 0; i < Size; ++i)
9738     if (Mask[i] >= 0)
9739       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9740   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9741          "Must not introduce lane crosses at this point!");
9742
9743   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9744 }
9745
9746 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9747 /// given mask.
9748 ///
9749 /// This returns true if the elements from a particular input are already in the
9750 /// slot required by the given mask and require no permutation.
9751 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9752   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9753   int Size = Mask.size();
9754   for (int i = 0; i < Size; ++i)
9755     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9756       return false;
9757
9758   return true;
9759 }
9760
9761 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9762                                             ArrayRef<int> Mask, SDValue V1,
9763                                             SDValue V2, SelectionDAG &DAG) {
9764
9765   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9766   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9767   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9768   int NumElts = VT.getVectorNumElements();
9769   bool ShufpdMask = true;
9770   bool CommutableMask = true;
9771   unsigned Immediate = 0;
9772   for (int i = 0; i < NumElts; ++i) {
9773     if (Mask[i] < 0)
9774       continue;
9775     int Val = (i & 6) + NumElts * (i & 1);
9776     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9777     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9778       ShufpdMask = false;
9779     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9780       CommutableMask = false;
9781     Immediate |= (Mask[i] % 2) << i;
9782   }
9783   if (ShufpdMask)
9784     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9785                        DAG.getConstant(Immediate, DL, MVT::i8));
9786   if (CommutableMask)
9787     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9788                        DAG.getConstant(Immediate, DL, MVT::i8));
9789   return SDValue();
9790 }
9791
9792 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9793 ///
9794 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9795 /// isn't available.
9796 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9797                                        const X86Subtarget *Subtarget,
9798                                        SelectionDAG &DAG) {
9799   SDLoc DL(Op);
9800   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9801   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9802   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9803   ArrayRef<int> Mask = SVOp->getMask();
9804   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9805
9806   SmallVector<int, 4> WidenedMask;
9807   if (canWidenShuffleElements(Mask, WidenedMask))
9808     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9809                                     DAG);
9810
9811   if (isSingleInputShuffleMask(Mask)) {
9812     // Check for being able to broadcast a single element.
9813     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9814                                                           Mask, Subtarget, DAG))
9815       return Broadcast;
9816
9817     // Use low duplicate instructions for masks that match their pattern.
9818     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9819       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9820
9821     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9822       // Non-half-crossing single input shuffles can be lowerid with an
9823       // interleaved permutation.
9824       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9825                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9826       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9827                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9828     }
9829
9830     // With AVX2 we have direct support for this permutation.
9831     if (Subtarget->hasAVX2())
9832       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9833                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9834
9835     // Otherwise, fall back.
9836     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9837                                                    DAG);
9838   }
9839
9840   // X86 has dedicated unpack instructions that can handle specific blend
9841   // operations: UNPCKH and UNPCKL.
9842   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9843     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9844   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9845     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9846   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9847     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9848   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9849     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9850
9851   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9852                                                 Subtarget, DAG))
9853     return Blend;
9854
9855   // Check if the blend happens to exactly fit that of SHUFPD.
9856   if (SDValue Op =
9857       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9858     return Op;
9859
9860   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9861   // shuffle. However, if we have AVX2 and either inputs are already in place,
9862   // we will be able to shuffle even across lanes the other input in a single
9863   // instruction so skip this pattern.
9864   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9865                                  isShuffleMaskInputInPlace(1, Mask))))
9866     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9867             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9868       return Result;
9869
9870   // If we have AVX2 then we always want to lower with a blend because an v4 we
9871   // can fully permute the elements.
9872   if (Subtarget->hasAVX2())
9873     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9874                                                       Mask, DAG);
9875
9876   // Otherwise fall back on generic lowering.
9877   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9878 }
9879
9880 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9881 ///
9882 /// This routine is only called when we have AVX2 and thus a reasonable
9883 /// instruction set for v4i64 shuffling..
9884 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9885                                        const X86Subtarget *Subtarget,
9886                                        SelectionDAG &DAG) {
9887   SDLoc DL(Op);
9888   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9889   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9890   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9891   ArrayRef<int> Mask = SVOp->getMask();
9892   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9893   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9894
9895   SmallVector<int, 4> WidenedMask;
9896   if (canWidenShuffleElements(Mask, WidenedMask))
9897     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9898                                     DAG);
9899
9900   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9901                                                 Subtarget, DAG))
9902     return Blend;
9903
9904   // Check for being able to broadcast a single element.
9905   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9906                                                         Mask, Subtarget, DAG))
9907     return Broadcast;
9908
9909   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9910   // use lower latency instructions that will operate on both 128-bit lanes.
9911   SmallVector<int, 2> RepeatedMask;
9912   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9913     if (isSingleInputShuffleMask(Mask)) {
9914       int PSHUFDMask[] = {-1, -1, -1, -1};
9915       for (int i = 0; i < 2; ++i)
9916         if (RepeatedMask[i] >= 0) {
9917           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9918           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9919         }
9920       return DAG.getBitcast(
9921           MVT::v4i64,
9922           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9923                       DAG.getBitcast(MVT::v8i32, V1),
9924                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9925     }
9926   }
9927
9928   // AVX2 provides a direct instruction for permuting a single input across
9929   // lanes.
9930   if (isSingleInputShuffleMask(Mask))
9931     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9932                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9933
9934   // Try to use shift instructions.
9935   if (SDValue Shift =
9936           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9937     return Shift;
9938
9939   // Use dedicated unpack instructions for masks that match their pattern.
9940   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9941     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9942   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9943     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9944   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9945     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9946   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9947     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9948
9949   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9950   // shuffle. However, if we have AVX2 and either inputs are already in place,
9951   // we will be able to shuffle even across lanes the other input in a single
9952   // instruction so skip this pattern.
9953   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9954                                  isShuffleMaskInputInPlace(1, Mask))))
9955     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9956             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9957       return Result;
9958
9959   // Otherwise fall back on generic blend lowering.
9960   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9961                                                     Mask, DAG);
9962 }
9963
9964 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9965 ///
9966 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9967 /// isn't available.
9968 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9969                                        const X86Subtarget *Subtarget,
9970                                        SelectionDAG &DAG) {
9971   SDLoc DL(Op);
9972   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9973   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9974   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9975   ArrayRef<int> Mask = SVOp->getMask();
9976   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9977
9978   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9979                                                 Subtarget, DAG))
9980     return Blend;
9981
9982   // Check for being able to broadcast a single element.
9983   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9984                                                         Mask, Subtarget, DAG))
9985     return Broadcast;
9986
9987   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9988   // options to efficiently lower the shuffle.
9989   SmallVector<int, 4> RepeatedMask;
9990   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9991     assert(RepeatedMask.size() == 4 &&
9992            "Repeated masks must be half the mask width!");
9993
9994     // Use even/odd duplicate instructions for masks that match their pattern.
9995     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9996       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9997     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9998       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9999
10000     if (isSingleInputShuffleMask(Mask))
10001       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10002                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10003
10004     // Use dedicated unpack instructions for masks that match their pattern.
10005     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10006       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10007     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10008       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10009     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10010       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10011     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10012       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10013
10014     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10015     // have already handled any direct blends. We also need to squash the
10016     // repeated mask into a simulated v4f32 mask.
10017     for (int i = 0; i < 4; ++i)
10018       if (RepeatedMask[i] >= 8)
10019         RepeatedMask[i] -= 4;
10020     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10021   }
10022
10023   // If we have a single input shuffle with different shuffle patterns in the
10024   // two 128-bit lanes use the variable mask to VPERMILPS.
10025   if (isSingleInputShuffleMask(Mask)) {
10026     SDValue VPermMask[8];
10027     for (int i = 0; i < 8; ++i)
10028       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10029                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10030     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10031       return DAG.getNode(
10032           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10033           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10034
10035     if (Subtarget->hasAVX2())
10036       return DAG.getNode(
10037           X86ISD::VPERMV, DL, MVT::v8f32,
10038           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10039                                                  MVT::v8i32, VPermMask)),
10040           V1);
10041
10042     // Otherwise, fall back.
10043     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10044                                                    DAG);
10045   }
10046
10047   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10048   // shuffle.
10049   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10050           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10051     return Result;
10052
10053   // If we have AVX2 then we always want to lower with a blend because at v8 we
10054   // can fully permute the elements.
10055   if (Subtarget->hasAVX2())
10056     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10057                                                       Mask, DAG);
10058
10059   // Otherwise fall back on generic lowering.
10060   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10061 }
10062
10063 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10064 ///
10065 /// This routine is only called when we have AVX2 and thus a reasonable
10066 /// instruction set for v8i32 shuffling..
10067 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10068                                        const X86Subtarget *Subtarget,
10069                                        SelectionDAG &DAG) {
10070   SDLoc DL(Op);
10071   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10072   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10073   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10074   ArrayRef<int> Mask = SVOp->getMask();
10075   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10076   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10077
10078   // Whenever we can lower this as a zext, that instruction is strictly faster
10079   // than any alternative. It also allows us to fold memory operands into the
10080   // shuffle in many cases.
10081   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10082                                                          Mask, Subtarget, DAG))
10083     return ZExt;
10084
10085   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10086                                                 Subtarget, DAG))
10087     return Blend;
10088
10089   // Check for being able to broadcast a single element.
10090   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10091                                                         Mask, Subtarget, DAG))
10092     return Broadcast;
10093
10094   // If the shuffle mask is repeated in each 128-bit lane we can use more
10095   // efficient instructions that mirror the shuffles across the two 128-bit
10096   // lanes.
10097   SmallVector<int, 4> RepeatedMask;
10098   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10099     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10100     if (isSingleInputShuffleMask(Mask))
10101       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10102                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10103
10104     // Use dedicated unpack instructions for masks that match their pattern.
10105     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10106       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10107     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10108       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10109     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10110       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10111     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10112       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10113   }
10114
10115   // Try to use shift instructions.
10116   if (SDValue Shift =
10117           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10118     return Shift;
10119
10120   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10121           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10122     return Rotate;
10123
10124   // If the shuffle patterns aren't repeated but it is a single input, directly
10125   // generate a cross-lane VPERMD instruction.
10126   if (isSingleInputShuffleMask(Mask)) {
10127     SDValue VPermMask[8];
10128     for (int i = 0; i < 8; ++i)
10129       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10130                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10131     return DAG.getNode(
10132         X86ISD::VPERMV, DL, MVT::v8i32,
10133         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10134   }
10135
10136   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10137   // shuffle.
10138   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10139           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10140     return Result;
10141
10142   // Otherwise fall back on generic blend lowering.
10143   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10144                                                     Mask, DAG);
10145 }
10146
10147 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10148 ///
10149 /// This routine is only called when we have AVX2 and thus a reasonable
10150 /// instruction set for v16i16 shuffling..
10151 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10152                                         const X86Subtarget *Subtarget,
10153                                         SelectionDAG &DAG) {
10154   SDLoc DL(Op);
10155   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10156   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10157   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10158   ArrayRef<int> Mask = SVOp->getMask();
10159   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10160   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10161
10162   // Whenever we can lower this as a zext, that instruction is strictly faster
10163   // than any alternative. It also allows us to fold memory operands into the
10164   // shuffle in many cases.
10165   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10166                                                          Mask, Subtarget, DAG))
10167     return ZExt;
10168
10169   // Check for being able to broadcast a single element.
10170   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10171                                                         Mask, Subtarget, DAG))
10172     return Broadcast;
10173
10174   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10175                                                 Subtarget, DAG))
10176     return Blend;
10177
10178   // Use dedicated unpack instructions for masks that match their pattern.
10179   if (isShuffleEquivalent(V1, V2, Mask,
10180                           {// First 128-bit lane:
10181                            0, 16, 1, 17, 2, 18, 3, 19,
10182                            // Second 128-bit lane:
10183                            8, 24, 9, 25, 10, 26, 11, 27}))
10184     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10185   if (isShuffleEquivalent(V1, V2, Mask,
10186                           {// First 128-bit lane:
10187                            4, 20, 5, 21, 6, 22, 7, 23,
10188                            // Second 128-bit lane:
10189                            12, 28, 13, 29, 14, 30, 15, 31}))
10190     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10191
10192   // Try to use shift instructions.
10193   if (SDValue Shift =
10194           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10195     return Shift;
10196
10197   // Try to use byte rotation instructions.
10198   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10199           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10200     return Rotate;
10201
10202   if (isSingleInputShuffleMask(Mask)) {
10203     // There are no generalized cross-lane shuffle operations available on i16
10204     // element types.
10205     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10206       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10207                                                      Mask, DAG);
10208
10209     SmallVector<int, 8> RepeatedMask;
10210     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10211       // As this is a single-input shuffle, the repeated mask should be
10212       // a strictly valid v8i16 mask that we can pass through to the v8i16
10213       // lowering to handle even the v16 case.
10214       return lowerV8I16GeneralSingleInputVectorShuffle(
10215           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10216     }
10217
10218     SDValue PSHUFBMask[32];
10219     for (int i = 0; i < 16; ++i) {
10220       if (Mask[i] == -1) {
10221         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10222         continue;
10223       }
10224
10225       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10226       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10227       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10228       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10229     }
10230     return DAG.getBitcast(MVT::v16i16,
10231                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10232                                       DAG.getBitcast(MVT::v32i8, V1),
10233                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10234                                                   MVT::v32i8, PSHUFBMask)));
10235   }
10236
10237   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10238   // shuffle.
10239   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10240           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10241     return Result;
10242
10243   // Otherwise fall back on generic lowering.
10244   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10245 }
10246
10247 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10248 ///
10249 /// This routine is only called when we have AVX2 and thus a reasonable
10250 /// instruction set for v32i8 shuffling..
10251 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10252                                        const X86Subtarget *Subtarget,
10253                                        SelectionDAG &DAG) {
10254   SDLoc DL(Op);
10255   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10256   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10257   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10258   ArrayRef<int> Mask = SVOp->getMask();
10259   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10260   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10261
10262   // Whenever we can lower this as a zext, that instruction is strictly faster
10263   // than any alternative. It also allows us to fold memory operands into the
10264   // shuffle in many cases.
10265   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10266                                                          Mask, Subtarget, DAG))
10267     return ZExt;
10268
10269   // Check for being able to broadcast a single element.
10270   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10271                                                         Mask, Subtarget, DAG))
10272     return Broadcast;
10273
10274   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10275                                                 Subtarget, DAG))
10276     return Blend;
10277
10278   // Use dedicated unpack instructions for masks that match their pattern.
10279   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10280   // 256-bit lanes.
10281   if (isShuffleEquivalent(
10282           V1, V2, Mask,
10283           {// First 128-bit lane:
10284            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10285            // Second 128-bit lane:
10286            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10287     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10288   if (isShuffleEquivalent(
10289           V1, V2, Mask,
10290           {// First 128-bit lane:
10291            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10292            // Second 128-bit lane:
10293            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10294     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10295
10296   // Try to use shift instructions.
10297   if (SDValue Shift =
10298           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10299     return Shift;
10300
10301   // Try to use byte rotation instructions.
10302   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10303           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10304     return Rotate;
10305
10306   if (isSingleInputShuffleMask(Mask)) {
10307     // There are no generalized cross-lane shuffle operations available on i8
10308     // element types.
10309     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10310       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10311                                                      Mask, DAG);
10312
10313     SDValue PSHUFBMask[32];
10314     for (int i = 0; i < 32; ++i)
10315       PSHUFBMask[i] =
10316           Mask[i] < 0
10317               ? DAG.getUNDEF(MVT::i8)
10318               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10319                                 MVT::i8);
10320
10321     return DAG.getNode(
10322         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10323         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10324   }
10325
10326   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10327   // shuffle.
10328   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10329           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10330     return Result;
10331
10332   // Otherwise fall back on generic lowering.
10333   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10334 }
10335
10336 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10337 ///
10338 /// This routine either breaks down the specific type of a 256-bit x86 vector
10339 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10340 /// together based on the available instructions.
10341 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10342                                         MVT VT, const X86Subtarget *Subtarget,
10343                                         SelectionDAG &DAG) {
10344   SDLoc DL(Op);
10345   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10346   ArrayRef<int> Mask = SVOp->getMask();
10347
10348   // If we have a single input to the zero element, insert that into V1 if we
10349   // can do so cheaply.
10350   int NumElts = VT.getVectorNumElements();
10351   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10352     return M >= NumElts;
10353   });
10354
10355   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10356     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10357                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10358       return Insertion;
10359
10360   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10361   // check for those subtargets here and avoid much of the subtarget querying in
10362   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10363   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10364   // floating point types there eventually, just immediately cast everything to
10365   // a float and operate entirely in that domain.
10366   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10367     int ElementBits = VT.getScalarSizeInBits();
10368     if (ElementBits < 32)
10369       // No floating point type available, decompose into 128-bit vectors.
10370       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10371
10372     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10373                                 VT.getVectorNumElements());
10374     V1 = DAG.getBitcast(FpVT, V1);
10375     V2 = DAG.getBitcast(FpVT, V2);
10376     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10377   }
10378
10379   switch (VT.SimpleTy) {
10380   case MVT::v4f64:
10381     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10382   case MVT::v4i64:
10383     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10384   case MVT::v8f32:
10385     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10386   case MVT::v8i32:
10387     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10388   case MVT::v16i16:
10389     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10390   case MVT::v32i8:
10391     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10392
10393   default:
10394     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10395   }
10396 }
10397
10398 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10399 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10400                                        const X86Subtarget *Subtarget,
10401                                        SelectionDAG &DAG) {
10402   SDLoc DL(Op);
10403   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10404   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10405   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10406   ArrayRef<int> Mask = SVOp->getMask();
10407   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10408
10409   // X86 has dedicated unpack instructions that can handle specific blend
10410   // operations: UNPCKH and UNPCKL.
10411   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10412     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10413   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10414     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10415
10416   // FIXME: Implement direct support for this type!
10417   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10418 }
10419
10420 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10421 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10422                                        const X86Subtarget *Subtarget,
10423                                        SelectionDAG &DAG) {
10424   SDLoc DL(Op);
10425   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10426   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10427   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10428   ArrayRef<int> Mask = SVOp->getMask();
10429   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10430
10431   // Use dedicated unpack instructions for masks that match their pattern.
10432   if (isShuffleEquivalent(V1, V2, Mask,
10433                           {// First 128-bit lane.
10434                            0, 16, 1, 17, 4, 20, 5, 21,
10435                            // Second 128-bit lane.
10436                            8, 24, 9, 25, 12, 28, 13, 29}))
10437     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10438   if (isShuffleEquivalent(V1, V2, Mask,
10439                           {// First 128-bit lane.
10440                            2, 18, 3, 19, 6, 22, 7, 23,
10441                            // Second 128-bit lane.
10442                            10, 26, 11, 27, 14, 30, 15, 31}))
10443     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10444
10445   // FIXME: Implement direct support for this type!
10446   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10447 }
10448
10449 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10450 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10451                                        const X86Subtarget *Subtarget,
10452                                        SelectionDAG &DAG) {
10453   SDLoc DL(Op);
10454   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10455   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10456   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10457   ArrayRef<int> Mask = SVOp->getMask();
10458   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10459
10460   // X86 has dedicated unpack instructions that can handle specific blend
10461   // operations: UNPCKH and UNPCKL.
10462   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10463     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10464   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10465     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10466
10467   // FIXME: Implement direct support for this type!
10468   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10469 }
10470
10471 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10472 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10473                                        const X86Subtarget *Subtarget,
10474                                        SelectionDAG &DAG) {
10475   SDLoc DL(Op);
10476   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10477   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10478   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10479   ArrayRef<int> Mask = SVOp->getMask();
10480   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10481
10482   // Use dedicated unpack instructions for masks that match their pattern.
10483   if (isShuffleEquivalent(V1, V2, Mask,
10484                           {// First 128-bit lane.
10485                            0, 16, 1, 17, 4, 20, 5, 21,
10486                            // Second 128-bit lane.
10487                            8, 24, 9, 25, 12, 28, 13, 29}))
10488     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10489   if (isShuffleEquivalent(V1, V2, Mask,
10490                           {// First 128-bit lane.
10491                            2, 18, 3, 19, 6, 22, 7, 23,
10492                            // Second 128-bit lane.
10493                            10, 26, 11, 27, 14, 30, 15, 31}))
10494     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10495
10496   // FIXME: Implement direct support for this type!
10497   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10498 }
10499
10500 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10501 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10502                                         const X86Subtarget *Subtarget,
10503                                         SelectionDAG &DAG) {
10504   SDLoc DL(Op);
10505   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10506   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10507   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10508   ArrayRef<int> Mask = SVOp->getMask();
10509   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10510   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10511
10512   // FIXME: Implement direct support for this type!
10513   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10514 }
10515
10516 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10517 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10518                                        const X86Subtarget *Subtarget,
10519                                        SelectionDAG &DAG) {
10520   SDLoc DL(Op);
10521   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10522   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10523   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10524   ArrayRef<int> Mask = SVOp->getMask();
10525   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10526   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10527
10528   // FIXME: Implement direct support for this type!
10529   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10530 }
10531
10532 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10533 ///
10534 /// This routine either breaks down the specific type of a 512-bit x86 vector
10535 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10536 /// together based on the available instructions.
10537 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10538                                         MVT VT, const X86Subtarget *Subtarget,
10539                                         SelectionDAG &DAG) {
10540   SDLoc DL(Op);
10541   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10542   ArrayRef<int> Mask = SVOp->getMask();
10543   assert(Subtarget->hasAVX512() &&
10544          "Cannot lower 512-bit vectors w/ basic ISA!");
10545
10546   // Check for being able to broadcast a single element.
10547   if (SDValue Broadcast =
10548           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10549     return Broadcast;
10550
10551   // Dispatch to each element type for lowering. If we don't have supprot for
10552   // specific element type shuffles at 512 bits, immediately split them and
10553   // lower them. Each lowering routine of a given type is allowed to assume that
10554   // the requisite ISA extensions for that element type are available.
10555   switch (VT.SimpleTy) {
10556   case MVT::v8f64:
10557     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10558   case MVT::v16f32:
10559     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10560   case MVT::v8i64:
10561     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10562   case MVT::v16i32:
10563     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10564   case MVT::v32i16:
10565     if (Subtarget->hasBWI())
10566       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10567     break;
10568   case MVT::v64i8:
10569     if (Subtarget->hasBWI())
10570       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10571     break;
10572
10573   default:
10574     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10575   }
10576
10577   // Otherwise fall back on splitting.
10578   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10579 }
10580
10581 /// \brief Top-level lowering for x86 vector shuffles.
10582 ///
10583 /// This handles decomposition, canonicalization, and lowering of all x86
10584 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10585 /// above in helper routines. The canonicalization attempts to widen shuffles
10586 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10587 /// s.t. only one of the two inputs needs to be tested, etc.
10588 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10589                                   SelectionDAG &DAG) {
10590   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10591   ArrayRef<int> Mask = SVOp->getMask();
10592   SDValue V1 = Op.getOperand(0);
10593   SDValue V2 = Op.getOperand(1);
10594   MVT VT = Op.getSimpleValueType();
10595   int NumElements = VT.getVectorNumElements();
10596   SDLoc dl(Op);
10597
10598   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10599
10600   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10601   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10602   if (V1IsUndef && V2IsUndef)
10603     return DAG.getUNDEF(VT);
10604
10605   // When we create a shuffle node we put the UNDEF node to second operand,
10606   // but in some cases the first operand may be transformed to UNDEF.
10607   // In this case we should just commute the node.
10608   if (V1IsUndef)
10609     return DAG.getCommutedVectorShuffle(*SVOp);
10610
10611   // Check for non-undef masks pointing at an undef vector and make the masks
10612   // undef as well. This makes it easier to match the shuffle based solely on
10613   // the mask.
10614   if (V2IsUndef)
10615     for (int M : Mask)
10616       if (M >= NumElements) {
10617         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10618         for (int &M : NewMask)
10619           if (M >= NumElements)
10620             M = -1;
10621         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10622       }
10623
10624   // We actually see shuffles that are entirely re-arrangements of a set of
10625   // zero inputs. This mostly happens while decomposing complex shuffles into
10626   // simple ones. Directly lower these as a buildvector of zeros.
10627   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10628   if (Zeroable.all())
10629     return getZeroVector(VT, Subtarget, DAG, dl);
10630
10631   // Try to collapse shuffles into using a vector type with fewer elements but
10632   // wider element types. We cap this to not form integers or floating point
10633   // elements wider than 64 bits, but it might be interesting to form i128
10634   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10635   SmallVector<int, 16> WidenedMask;
10636   if (VT.getScalarSizeInBits() < 64 &&
10637       canWidenShuffleElements(Mask, WidenedMask)) {
10638     MVT NewEltVT = VT.isFloatingPoint()
10639                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10640                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10641     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10642     // Make sure that the new vector type is legal. For example, v2f64 isn't
10643     // legal on SSE1.
10644     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10645       V1 = DAG.getBitcast(NewVT, V1);
10646       V2 = DAG.getBitcast(NewVT, V2);
10647       return DAG.getBitcast(
10648           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10649     }
10650   }
10651
10652   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10653   for (int M : SVOp->getMask())
10654     if (M < 0)
10655       ++NumUndefElements;
10656     else if (M < NumElements)
10657       ++NumV1Elements;
10658     else
10659       ++NumV2Elements;
10660
10661   // Commute the shuffle as needed such that more elements come from V1 than
10662   // V2. This allows us to match the shuffle pattern strictly on how many
10663   // elements come from V1 without handling the symmetric cases.
10664   if (NumV2Elements > NumV1Elements)
10665     return DAG.getCommutedVectorShuffle(*SVOp);
10666
10667   // When the number of V1 and V2 elements are the same, try to minimize the
10668   // number of uses of V2 in the low half of the vector. When that is tied,
10669   // ensure that the sum of indices for V1 is equal to or lower than the sum
10670   // indices for V2. When those are equal, try to ensure that the number of odd
10671   // indices for V1 is lower than the number of odd indices for V2.
10672   if (NumV1Elements == NumV2Elements) {
10673     int LowV1Elements = 0, LowV2Elements = 0;
10674     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10675       if (M >= NumElements)
10676         ++LowV2Elements;
10677       else if (M >= 0)
10678         ++LowV1Elements;
10679     if (LowV2Elements > LowV1Elements) {
10680       return DAG.getCommutedVectorShuffle(*SVOp);
10681     } else if (LowV2Elements == LowV1Elements) {
10682       int SumV1Indices = 0, SumV2Indices = 0;
10683       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10684         if (SVOp->getMask()[i] >= NumElements)
10685           SumV2Indices += i;
10686         else if (SVOp->getMask()[i] >= 0)
10687           SumV1Indices += i;
10688       if (SumV2Indices < SumV1Indices) {
10689         return DAG.getCommutedVectorShuffle(*SVOp);
10690       } else if (SumV2Indices == SumV1Indices) {
10691         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10692         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10693           if (SVOp->getMask()[i] >= NumElements)
10694             NumV2OddIndices += i % 2;
10695           else if (SVOp->getMask()[i] >= 0)
10696             NumV1OddIndices += i % 2;
10697         if (NumV2OddIndices < NumV1OddIndices)
10698           return DAG.getCommutedVectorShuffle(*SVOp);
10699       }
10700     }
10701   }
10702
10703   // For each vector width, delegate to a specialized lowering routine.
10704   if (VT.getSizeInBits() == 128)
10705     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10706
10707   if (VT.getSizeInBits() == 256)
10708     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10709
10710   // Force AVX-512 vectors to be scalarized for now.
10711   // FIXME: Implement AVX-512 support!
10712   if (VT.getSizeInBits() == 512)
10713     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10714
10715   llvm_unreachable("Unimplemented!");
10716 }
10717
10718 // This function assumes its argument is a BUILD_VECTOR of constants or
10719 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10720 // true.
10721 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10722                                     unsigned &MaskValue) {
10723   MaskValue = 0;
10724   unsigned NumElems = BuildVector->getNumOperands();
10725   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10726   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10727   unsigned NumElemsInLane = NumElems / NumLanes;
10728
10729   // Blend for v16i16 should be symetric for the both lanes.
10730   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10731     SDValue EltCond = BuildVector->getOperand(i);
10732     SDValue SndLaneEltCond =
10733         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10734
10735     int Lane1Cond = -1, Lane2Cond = -1;
10736     if (isa<ConstantSDNode>(EltCond))
10737       Lane1Cond = !isZero(EltCond);
10738     if (isa<ConstantSDNode>(SndLaneEltCond))
10739       Lane2Cond = !isZero(SndLaneEltCond);
10740
10741     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10742       // Lane1Cond != 0, means we want the first argument.
10743       // Lane1Cond == 0, means we want the second argument.
10744       // The encoding of this argument is 0 for the first argument, 1
10745       // for the second. Therefore, invert the condition.
10746       MaskValue |= !Lane1Cond << i;
10747     else if (Lane1Cond < 0)
10748       MaskValue |= !Lane2Cond << i;
10749     else
10750       return false;
10751   }
10752   return true;
10753 }
10754
10755 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10756 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10757                                            const X86Subtarget *Subtarget,
10758                                            SelectionDAG &DAG) {
10759   SDValue Cond = Op.getOperand(0);
10760   SDValue LHS = Op.getOperand(1);
10761   SDValue RHS = Op.getOperand(2);
10762   SDLoc dl(Op);
10763   MVT VT = Op.getSimpleValueType();
10764
10765   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10766     return SDValue();
10767   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10768
10769   // Only non-legal VSELECTs reach this lowering, convert those into generic
10770   // shuffles and re-use the shuffle lowering path for blends.
10771   SmallVector<int, 32> Mask;
10772   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10773     SDValue CondElt = CondBV->getOperand(i);
10774     Mask.push_back(
10775         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10776   }
10777   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10778 }
10779
10780 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10781   // A vselect where all conditions and data are constants can be optimized into
10782   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10783   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10784       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10785       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10786     return SDValue();
10787
10788   // Try to lower this to a blend-style vector shuffle. This can handle all
10789   // constant condition cases.
10790   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10791     return BlendOp;
10792
10793   // Variable blends are only legal from SSE4.1 onward.
10794   if (!Subtarget->hasSSE41())
10795     return SDValue();
10796
10797   // Only some types will be legal on some subtargets. If we can emit a legal
10798   // VSELECT-matching blend, return Op, and but if we need to expand, return
10799   // a null value.
10800   switch (Op.getSimpleValueType().SimpleTy) {
10801   default:
10802     // Most of the vector types have blends past SSE4.1.
10803     return Op;
10804
10805   case MVT::v32i8:
10806     // The byte blends for AVX vectors were introduced only in AVX2.
10807     if (Subtarget->hasAVX2())
10808       return Op;
10809
10810     return SDValue();
10811
10812   case MVT::v8i16:
10813   case MVT::v16i16:
10814     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10815     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10816       return Op;
10817
10818     // FIXME: We should custom lower this by fixing the condition and using i8
10819     // blends.
10820     return SDValue();
10821   }
10822 }
10823
10824 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10825   MVT VT = Op.getSimpleValueType();
10826   SDLoc dl(Op);
10827
10828   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10829     return SDValue();
10830
10831   if (VT.getSizeInBits() == 8) {
10832     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10833                                   Op.getOperand(0), Op.getOperand(1));
10834     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10835                                   DAG.getValueType(VT));
10836     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10837   }
10838
10839   if (VT.getSizeInBits() == 16) {
10840     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10841     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10842     if (Idx == 0)
10843       return DAG.getNode(
10844           ISD::TRUNCATE, dl, MVT::i16,
10845           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10846                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10847                       Op.getOperand(1)));
10848     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10849                                   Op.getOperand(0), Op.getOperand(1));
10850     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10851                                   DAG.getValueType(VT));
10852     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10853   }
10854
10855   if (VT == MVT::f32) {
10856     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10857     // the result back to FR32 register. It's only worth matching if the
10858     // result has a single use which is a store or a bitcast to i32.  And in
10859     // the case of a store, it's not worth it if the index is a constant 0,
10860     // because a MOVSSmr can be used instead, which is smaller and faster.
10861     if (!Op.hasOneUse())
10862       return SDValue();
10863     SDNode *User = *Op.getNode()->use_begin();
10864     if ((User->getOpcode() != ISD::STORE ||
10865          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10866           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10867         (User->getOpcode() != ISD::BITCAST ||
10868          User->getValueType(0) != MVT::i32))
10869       return SDValue();
10870     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10871                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10872                                   Op.getOperand(1));
10873     return DAG.getBitcast(MVT::f32, Extract);
10874   }
10875
10876   if (VT == MVT::i32 || VT == MVT::i64) {
10877     // ExtractPS/pextrq works with constant index.
10878     if (isa<ConstantSDNode>(Op.getOperand(1)))
10879       return Op;
10880   }
10881   return SDValue();
10882 }
10883
10884 /// Extract one bit from mask vector, like v16i1 or v8i1.
10885 /// AVX-512 feature.
10886 SDValue
10887 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10888   SDValue Vec = Op.getOperand(0);
10889   SDLoc dl(Vec);
10890   MVT VecVT = Vec.getSimpleValueType();
10891   SDValue Idx = Op.getOperand(1);
10892   MVT EltVT = Op.getSimpleValueType();
10893
10894   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10895   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10896          "Unexpected vector type in ExtractBitFromMaskVector");
10897
10898   // variable index can't be handled in mask registers,
10899   // extend vector to VR512
10900   if (!isa<ConstantSDNode>(Idx)) {
10901     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10902     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10903     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10904                               ExtVT.getVectorElementType(), Ext, Idx);
10905     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10906   }
10907
10908   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10909   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10910   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10911     rc = getRegClassFor(MVT::v16i1);
10912   unsigned MaxSift = rc->getSize()*8 - 1;
10913   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10914                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10915   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10916                     DAG.getConstant(MaxSift, dl, MVT::i8));
10917   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10918                        DAG.getIntPtrConstant(0, dl));
10919 }
10920
10921 SDValue
10922 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10923                                            SelectionDAG &DAG) const {
10924   SDLoc dl(Op);
10925   SDValue Vec = Op.getOperand(0);
10926   MVT VecVT = Vec.getSimpleValueType();
10927   SDValue Idx = Op.getOperand(1);
10928
10929   if (Op.getSimpleValueType() == MVT::i1)
10930     return ExtractBitFromMaskVector(Op, DAG);
10931
10932   if (!isa<ConstantSDNode>(Idx)) {
10933     if (VecVT.is512BitVector() ||
10934         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10935          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10936
10937       MVT MaskEltVT =
10938         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10939       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10940                                     MaskEltVT.getSizeInBits());
10941
10942       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10943       auto PtrVT = getPointerTy(DAG.getDataLayout());
10944       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10945                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10946                                  DAG.getConstant(0, dl, PtrVT));
10947       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10948       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10949                          DAG.getConstant(0, dl, PtrVT));
10950     }
10951     return SDValue();
10952   }
10953
10954   // If this is a 256-bit vector result, first extract the 128-bit vector and
10955   // then extract the element from the 128-bit vector.
10956   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10957
10958     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10959     // Get the 128-bit vector.
10960     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10961     MVT EltVT = VecVT.getVectorElementType();
10962
10963     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10964
10965     //if (IdxVal >= NumElems/2)
10966     //  IdxVal -= NumElems/2;
10967     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10968     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10969                        DAG.getConstant(IdxVal, dl, MVT::i32));
10970   }
10971
10972   assert(VecVT.is128BitVector() && "Unexpected vector length");
10973
10974   if (Subtarget->hasSSE41())
10975     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10976       return Res;
10977
10978   MVT VT = Op.getSimpleValueType();
10979   // TODO: handle v16i8.
10980   if (VT.getSizeInBits() == 16) {
10981     SDValue Vec = Op.getOperand(0);
10982     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10983     if (Idx == 0)
10984       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10985                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10986                                      DAG.getBitcast(MVT::v4i32, Vec),
10987                                      Op.getOperand(1)));
10988     // Transform it so it match pextrw which produces a 32-bit result.
10989     MVT EltVT = MVT::i32;
10990     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10991                                   Op.getOperand(0), Op.getOperand(1));
10992     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10993                                   DAG.getValueType(VT));
10994     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10995   }
10996
10997   if (VT.getSizeInBits() == 32) {
10998     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10999     if (Idx == 0)
11000       return Op;
11001
11002     // SHUFPS the element to the lowest double word, then movss.
11003     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11004     MVT VVT = Op.getOperand(0).getSimpleValueType();
11005     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11006                                        DAG.getUNDEF(VVT), Mask);
11007     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11008                        DAG.getIntPtrConstant(0, dl));
11009   }
11010
11011   if (VT.getSizeInBits() == 64) {
11012     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11013     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11014     //        to match extract_elt for f64.
11015     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11016     if (Idx == 0)
11017       return Op;
11018
11019     // UNPCKHPD the element to the lowest double word, then movsd.
11020     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11021     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11022     int Mask[2] = { 1, -1 };
11023     MVT VVT = Op.getOperand(0).getSimpleValueType();
11024     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11025                                        DAG.getUNDEF(VVT), Mask);
11026     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11027                        DAG.getIntPtrConstant(0, dl));
11028   }
11029
11030   return SDValue();
11031 }
11032
11033 /// Insert one bit to mask vector, like v16i1 or v8i1.
11034 /// AVX-512 feature.
11035 SDValue
11036 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11037   SDLoc dl(Op);
11038   SDValue Vec = Op.getOperand(0);
11039   SDValue Elt = Op.getOperand(1);
11040   SDValue Idx = Op.getOperand(2);
11041   MVT VecVT = Vec.getSimpleValueType();
11042
11043   if (!isa<ConstantSDNode>(Idx)) {
11044     // Non constant index. Extend source and destination,
11045     // insert element and then truncate the result.
11046     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11047     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11048     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11049       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11050       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11051     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11052   }
11053
11054   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11055   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11056   if (IdxVal)
11057     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11058                            DAG.getConstant(IdxVal, dl, MVT::i8));
11059   if (Vec.getOpcode() == ISD::UNDEF)
11060     return EltInVec;
11061   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11062 }
11063
11064 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11065                                                   SelectionDAG &DAG) const {
11066   MVT VT = Op.getSimpleValueType();
11067   MVT EltVT = VT.getVectorElementType();
11068
11069   if (EltVT == MVT::i1)
11070     return InsertBitToMaskVector(Op, DAG);
11071
11072   SDLoc dl(Op);
11073   SDValue N0 = Op.getOperand(0);
11074   SDValue N1 = Op.getOperand(1);
11075   SDValue N2 = Op.getOperand(2);
11076   if (!isa<ConstantSDNode>(N2))
11077     return SDValue();
11078   auto *N2C = cast<ConstantSDNode>(N2);
11079   unsigned IdxVal = N2C->getZExtValue();
11080
11081   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11082   // into that, and then insert the subvector back into the result.
11083   if (VT.is256BitVector() || VT.is512BitVector()) {
11084     // With a 256-bit vector, we can insert into the zero element efficiently
11085     // using a blend if we have AVX or AVX2 and the right data type.
11086     if (VT.is256BitVector() && IdxVal == 0) {
11087       // TODO: It is worthwhile to cast integer to floating point and back
11088       // and incur a domain crossing penalty if that's what we'll end up
11089       // doing anyway after extracting to a 128-bit vector.
11090       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11091           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11092         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11093         N2 = DAG.getIntPtrConstant(1, dl);
11094         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11095       }
11096     }
11097
11098     // Get the desired 128-bit vector chunk.
11099     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11100
11101     // Insert the element into the desired chunk.
11102     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11103     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11104
11105     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11106                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11107
11108     // Insert the changed part back into the bigger vector
11109     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11110   }
11111   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11112
11113   if (Subtarget->hasSSE41()) {
11114     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11115       unsigned Opc;
11116       if (VT == MVT::v8i16) {
11117         Opc = X86ISD::PINSRW;
11118       } else {
11119         assert(VT == MVT::v16i8);
11120         Opc = X86ISD::PINSRB;
11121       }
11122
11123       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11124       // argument.
11125       if (N1.getValueType() != MVT::i32)
11126         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11127       if (N2.getValueType() != MVT::i32)
11128         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11129       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11130     }
11131
11132     if (EltVT == MVT::f32) {
11133       // Bits [7:6] of the constant are the source select. This will always be
11134       //   zero here. The DAG Combiner may combine an extract_elt index into
11135       //   these bits. For example (insert (extract, 3), 2) could be matched by
11136       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11137       // Bits [5:4] of the constant are the destination select. This is the
11138       //   value of the incoming immediate.
11139       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11140       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11141
11142       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11143       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11144         // If this is an insertion of 32-bits into the low 32-bits of
11145         // a vector, we prefer to generate a blend with immediate rather
11146         // than an insertps. Blends are simpler operations in hardware and so
11147         // will always have equal or better performance than insertps.
11148         // But if optimizing for size and there's a load folding opportunity,
11149         // generate insertps because blendps does not have a 32-bit memory
11150         // operand form.
11151         N2 = DAG.getIntPtrConstant(1, dl);
11152         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11153         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11154       }
11155       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11156       // Create this as a scalar to vector..
11157       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11158       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11159     }
11160
11161     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11162       // PINSR* works with constant index.
11163       return Op;
11164     }
11165   }
11166
11167   if (EltVT == MVT::i8)
11168     return SDValue();
11169
11170   if (EltVT.getSizeInBits() == 16) {
11171     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11172     // as its second argument.
11173     if (N1.getValueType() != MVT::i32)
11174       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11175     if (N2.getValueType() != MVT::i32)
11176       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11177     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11178   }
11179   return SDValue();
11180 }
11181
11182 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11183   SDLoc dl(Op);
11184   MVT OpVT = Op.getSimpleValueType();
11185
11186   // If this is a 256-bit vector result, first insert into a 128-bit
11187   // vector and then insert into the 256-bit vector.
11188   if (!OpVT.is128BitVector()) {
11189     // Insert into a 128-bit vector.
11190     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11191     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11192                                  OpVT.getVectorNumElements() / SizeFactor);
11193
11194     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11195
11196     // Insert the 128-bit vector.
11197     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11198   }
11199
11200   if (OpVT == MVT::v1i64 &&
11201       Op.getOperand(0).getValueType() == MVT::i64)
11202     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11203
11204   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11205   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11206   return DAG.getBitcast(
11207       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11208 }
11209
11210 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11211 // a simple subregister reference or explicit instructions to grab
11212 // upper bits of a vector.
11213 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11214                                       SelectionDAG &DAG) {
11215   SDLoc dl(Op);
11216   SDValue In =  Op.getOperand(0);
11217   SDValue Idx = Op.getOperand(1);
11218   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11219   MVT ResVT   = Op.getSimpleValueType();
11220   MVT InVT    = In.getSimpleValueType();
11221
11222   if (Subtarget->hasFp256()) {
11223     if (ResVT.is128BitVector() &&
11224         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11225         isa<ConstantSDNode>(Idx)) {
11226       return Extract128BitVector(In, IdxVal, DAG, dl);
11227     }
11228     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11229         isa<ConstantSDNode>(Idx)) {
11230       return Extract256BitVector(In, IdxVal, DAG, dl);
11231     }
11232   }
11233   return SDValue();
11234 }
11235
11236 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11237 // simple superregister reference or explicit instructions to insert
11238 // the upper bits of a vector.
11239 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11240                                      SelectionDAG &DAG) {
11241   if (!Subtarget->hasAVX())
11242     return SDValue();
11243
11244   SDLoc dl(Op);
11245   SDValue Vec = Op.getOperand(0);
11246   SDValue SubVec = Op.getOperand(1);
11247   SDValue Idx = Op.getOperand(2);
11248
11249   if (!isa<ConstantSDNode>(Idx))
11250     return SDValue();
11251
11252   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11253   MVT OpVT = Op.getSimpleValueType();
11254   MVT SubVecVT = SubVec.getSimpleValueType();
11255
11256   // Fold two 16-byte subvector loads into one 32-byte load:
11257   // (insert_subvector (insert_subvector undef, (load addr), 0),
11258   //                   (load addr + 16), Elts/2)
11259   // --> load32 addr
11260   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11261       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11262       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11263       !Subtarget->isUnalignedMem32Slow()) {
11264     SDValue SubVec2 = Vec.getOperand(1);
11265     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11266       if (Idx2->getZExtValue() == 0) {
11267         SDValue Ops[] = { SubVec2, SubVec };
11268         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11269           return Ld;
11270       }
11271     }
11272   }
11273
11274   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11275       SubVecVT.is128BitVector())
11276     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11277
11278   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11279     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11280
11281   if (OpVT.getVectorElementType() == MVT::i1) {
11282     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11283       return Op;
11284     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11285     SDValue Undef = DAG.getUNDEF(OpVT);
11286     unsigned NumElems = OpVT.getVectorNumElements();
11287     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11288
11289     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11290       // Zero upper bits of the Vec
11291       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11292       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11293
11294       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11295                                  SubVec, ZeroIdx);
11296       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11297       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11298     }
11299     if (IdxVal == 0) {
11300       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11301                                  SubVec, ZeroIdx);
11302       // Zero upper bits of the Vec2
11303       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11304       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11305       // Zero lower bits of the Vec
11306       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11307       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11308       // Merge them together
11309       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11310     }
11311   }
11312   return SDValue();
11313 }
11314
11315 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11316 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11317 // one of the above mentioned nodes. It has to be wrapped because otherwise
11318 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11319 // be used to form addressing mode. These wrapped nodes will be selected
11320 // into MOV32ri.
11321 SDValue
11322 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11323   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11324
11325   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11326   // global base reg.
11327   unsigned char OpFlag = 0;
11328   unsigned WrapperKind = X86ISD::Wrapper;
11329   CodeModel::Model M = DAG.getTarget().getCodeModel();
11330
11331   if (Subtarget->isPICStyleRIPRel() &&
11332       (M == CodeModel::Small || M == CodeModel::Kernel))
11333     WrapperKind = X86ISD::WrapperRIP;
11334   else if (Subtarget->isPICStyleGOT())
11335     OpFlag = X86II::MO_GOTOFF;
11336   else if (Subtarget->isPICStyleStubPIC())
11337     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11338
11339   auto PtrVT = getPointerTy(DAG.getDataLayout());
11340   SDValue Result = DAG.getTargetConstantPool(
11341       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11342   SDLoc DL(CP);
11343   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11344   // With PIC, the address is actually $g + Offset.
11345   if (OpFlag) {
11346     Result =
11347         DAG.getNode(ISD::ADD, DL, PtrVT,
11348                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11349   }
11350
11351   return Result;
11352 }
11353
11354 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11355   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11356
11357   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11358   // global base reg.
11359   unsigned char OpFlag = 0;
11360   unsigned WrapperKind = X86ISD::Wrapper;
11361   CodeModel::Model M = DAG.getTarget().getCodeModel();
11362
11363   if (Subtarget->isPICStyleRIPRel() &&
11364       (M == CodeModel::Small || M == CodeModel::Kernel))
11365     WrapperKind = X86ISD::WrapperRIP;
11366   else if (Subtarget->isPICStyleGOT())
11367     OpFlag = X86II::MO_GOTOFF;
11368   else if (Subtarget->isPICStyleStubPIC())
11369     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11370
11371   auto PtrVT = getPointerTy(DAG.getDataLayout());
11372   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11373   SDLoc DL(JT);
11374   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11375
11376   // With PIC, the address is actually $g + Offset.
11377   if (OpFlag)
11378     Result =
11379         DAG.getNode(ISD::ADD, DL, PtrVT,
11380                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11381
11382   return Result;
11383 }
11384
11385 SDValue
11386 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11387   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11388
11389   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11390   // global base reg.
11391   unsigned char OpFlag = 0;
11392   unsigned WrapperKind = X86ISD::Wrapper;
11393   CodeModel::Model M = DAG.getTarget().getCodeModel();
11394
11395   if (Subtarget->isPICStyleRIPRel() &&
11396       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11397     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11398       OpFlag = X86II::MO_GOTPCREL;
11399     WrapperKind = X86ISD::WrapperRIP;
11400   } else if (Subtarget->isPICStyleGOT()) {
11401     OpFlag = X86II::MO_GOT;
11402   } else if (Subtarget->isPICStyleStubPIC()) {
11403     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11404   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11405     OpFlag = X86II::MO_DARWIN_NONLAZY;
11406   }
11407
11408   auto PtrVT = getPointerTy(DAG.getDataLayout());
11409   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11410
11411   SDLoc DL(Op);
11412   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11413
11414   // With PIC, the address is actually $g + Offset.
11415   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11416       !Subtarget->is64Bit()) {
11417     Result =
11418         DAG.getNode(ISD::ADD, DL, PtrVT,
11419                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11420   }
11421
11422   // For symbols that require a load from a stub to get the address, emit the
11423   // load.
11424   if (isGlobalStubReference(OpFlag))
11425     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11426                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11427                          false, false, false, 0);
11428
11429   return Result;
11430 }
11431
11432 SDValue
11433 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11434   // Create the TargetBlockAddressAddress node.
11435   unsigned char OpFlags =
11436     Subtarget->ClassifyBlockAddressReference();
11437   CodeModel::Model M = DAG.getTarget().getCodeModel();
11438   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11439   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11440   SDLoc dl(Op);
11441   auto PtrVT = getPointerTy(DAG.getDataLayout());
11442   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11443
11444   if (Subtarget->isPICStyleRIPRel() &&
11445       (M == CodeModel::Small || M == CodeModel::Kernel))
11446     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11447   else
11448     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11449
11450   // With PIC, the address is actually $g + Offset.
11451   if (isGlobalRelativeToPICBase(OpFlags)) {
11452     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11453                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11454   }
11455
11456   return Result;
11457 }
11458
11459 SDValue
11460 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11461                                       int64_t Offset, SelectionDAG &DAG) const {
11462   // Create the TargetGlobalAddress node, folding in the constant
11463   // offset if it is legal.
11464   unsigned char OpFlags =
11465       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11466   CodeModel::Model M = DAG.getTarget().getCodeModel();
11467   auto PtrVT = getPointerTy(DAG.getDataLayout());
11468   SDValue Result;
11469   if (OpFlags == X86II::MO_NO_FLAG &&
11470       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11471     // A direct static reference to a global.
11472     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11473     Offset = 0;
11474   } else {
11475     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11476   }
11477
11478   if (Subtarget->isPICStyleRIPRel() &&
11479       (M == CodeModel::Small || M == CodeModel::Kernel))
11480     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11481   else
11482     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11483
11484   // With PIC, the address is actually $g + Offset.
11485   if (isGlobalRelativeToPICBase(OpFlags)) {
11486     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11487                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11488   }
11489
11490   // For globals that require a load from a stub to get the address, emit the
11491   // load.
11492   if (isGlobalStubReference(OpFlags))
11493     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11494                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11495                          false, false, false, 0);
11496
11497   // If there was a non-zero offset that we didn't fold, create an explicit
11498   // addition for it.
11499   if (Offset != 0)
11500     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11501                          DAG.getConstant(Offset, dl, PtrVT));
11502
11503   return Result;
11504 }
11505
11506 SDValue
11507 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11508   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11509   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11510   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11511 }
11512
11513 static SDValue
11514 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11515            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11516            unsigned char OperandFlags, bool LocalDynamic = false) {
11517   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11518   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11519   SDLoc dl(GA);
11520   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11521                                            GA->getValueType(0),
11522                                            GA->getOffset(),
11523                                            OperandFlags);
11524
11525   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11526                                            : X86ISD::TLSADDR;
11527
11528   if (InFlag) {
11529     SDValue Ops[] = { Chain,  TGA, *InFlag };
11530     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11531   } else {
11532     SDValue Ops[]  = { Chain, TGA };
11533     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11534   }
11535
11536   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11537   MFI->setAdjustsStack(true);
11538   MFI->setHasCalls(true);
11539
11540   SDValue Flag = Chain.getValue(1);
11541   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11542 }
11543
11544 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11545 static SDValue
11546 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11547                                 const EVT PtrVT) {
11548   SDValue InFlag;
11549   SDLoc dl(GA);  // ? function entry point might be better
11550   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11551                                    DAG.getNode(X86ISD::GlobalBaseReg,
11552                                                SDLoc(), PtrVT), InFlag);
11553   InFlag = Chain.getValue(1);
11554
11555   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11556 }
11557
11558 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11559 static SDValue
11560 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11561                                 const EVT PtrVT) {
11562   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11563                     X86::RAX, X86II::MO_TLSGD);
11564 }
11565
11566 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11567                                            SelectionDAG &DAG,
11568                                            const EVT PtrVT,
11569                                            bool is64Bit) {
11570   SDLoc dl(GA);
11571
11572   // Get the start address of the TLS block for this module.
11573   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11574       .getInfo<X86MachineFunctionInfo>();
11575   MFI->incNumLocalDynamicTLSAccesses();
11576
11577   SDValue Base;
11578   if (is64Bit) {
11579     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11580                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11581   } else {
11582     SDValue InFlag;
11583     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11584         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11585     InFlag = Chain.getValue(1);
11586     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11587                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11588   }
11589
11590   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11591   // of Base.
11592
11593   // Build x@dtpoff.
11594   unsigned char OperandFlags = X86II::MO_DTPOFF;
11595   unsigned WrapperKind = X86ISD::Wrapper;
11596   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11597                                            GA->getValueType(0),
11598                                            GA->getOffset(), OperandFlags);
11599   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11600
11601   // Add x@dtpoff with the base.
11602   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11603 }
11604
11605 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11606 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11607                                    const EVT PtrVT, TLSModel::Model model,
11608                                    bool is64Bit, bool isPIC) {
11609   SDLoc dl(GA);
11610
11611   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11612   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11613                                                          is64Bit ? 257 : 256));
11614
11615   SDValue ThreadPointer =
11616       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11617                   MachinePointerInfo(Ptr), false, false, false, 0);
11618
11619   unsigned char OperandFlags = 0;
11620   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11621   // initialexec.
11622   unsigned WrapperKind = X86ISD::Wrapper;
11623   if (model == TLSModel::LocalExec) {
11624     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11625   } else if (model == TLSModel::InitialExec) {
11626     if (is64Bit) {
11627       OperandFlags = X86II::MO_GOTTPOFF;
11628       WrapperKind = X86ISD::WrapperRIP;
11629     } else {
11630       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11631     }
11632   } else {
11633     llvm_unreachable("Unexpected model");
11634   }
11635
11636   // emit "addl x@ntpoff,%eax" (local exec)
11637   // or "addl x@indntpoff,%eax" (initial exec)
11638   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11639   SDValue TGA =
11640       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11641                                  GA->getOffset(), OperandFlags);
11642   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11643
11644   if (model == TLSModel::InitialExec) {
11645     if (isPIC && !is64Bit) {
11646       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11647                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11648                            Offset);
11649     }
11650
11651     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11652                          MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11653                          false, false, false, 0);
11654   }
11655
11656   // The address of the thread local variable is the add of the thread
11657   // pointer with the offset of the variable.
11658   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11659 }
11660
11661 SDValue
11662 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11663
11664   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11665   const GlobalValue *GV = GA->getGlobal();
11666   auto PtrVT = getPointerTy(DAG.getDataLayout());
11667
11668   if (Subtarget->isTargetELF()) {
11669     if (DAG.getTarget().Options.EmulatedTLS)
11670       return LowerToTLSEmulatedModel(GA, DAG);
11671     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11672     switch (model) {
11673       case TLSModel::GeneralDynamic:
11674         if (Subtarget->is64Bit())
11675           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11676         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11677       case TLSModel::LocalDynamic:
11678         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11679                                            Subtarget->is64Bit());
11680       case TLSModel::InitialExec:
11681       case TLSModel::LocalExec:
11682         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11683                                    DAG.getTarget().getRelocationModel() ==
11684                                        Reloc::PIC_);
11685     }
11686     llvm_unreachable("Unknown TLS model.");
11687   }
11688
11689   if (Subtarget->isTargetDarwin()) {
11690     // Darwin only has one model of TLS.  Lower to that.
11691     unsigned char OpFlag = 0;
11692     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11693                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11694
11695     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11696     // global base reg.
11697     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11698                  !Subtarget->is64Bit();
11699     if (PIC32)
11700       OpFlag = X86II::MO_TLVP_PIC_BASE;
11701     else
11702       OpFlag = X86II::MO_TLVP;
11703     SDLoc DL(Op);
11704     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11705                                                 GA->getValueType(0),
11706                                                 GA->getOffset(), OpFlag);
11707     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11708
11709     // With PIC32, the address is actually $g + Offset.
11710     if (PIC32)
11711       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11712                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11713                            Offset);
11714
11715     // Lowering the machine isd will make sure everything is in the right
11716     // location.
11717     SDValue Chain = DAG.getEntryNode();
11718     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11719     SDValue Args[] = { Chain, Offset };
11720     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11721
11722     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11723     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11724     MFI->setAdjustsStack(true);
11725
11726     // And our return value (tls address) is in the standard call return value
11727     // location.
11728     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11729     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11730   }
11731
11732   if (Subtarget->isTargetKnownWindowsMSVC() ||
11733       Subtarget->isTargetWindowsGNU()) {
11734     // Just use the implicit TLS architecture
11735     // Need to generate someting similar to:
11736     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11737     //                                  ; from TEB
11738     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11739     //   mov     rcx, qword [rdx+rcx*8]
11740     //   mov     eax, .tls$:tlsvar
11741     //   [rax+rcx] contains the address
11742     // Windows 64bit: gs:0x58
11743     // Windows 32bit: fs:__tls_array
11744
11745     SDLoc dl(GA);
11746     SDValue Chain = DAG.getEntryNode();
11747
11748     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11749     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11750     // use its literal value of 0x2C.
11751     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11752                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11753                                                              256)
11754                                         : Type::getInt32PtrTy(*DAG.getContext(),
11755                                                               257));
11756
11757     SDValue TlsArray = Subtarget->is64Bit()
11758                            ? DAG.getIntPtrConstant(0x58, dl)
11759                            : (Subtarget->isTargetWindowsGNU()
11760                                   ? DAG.getIntPtrConstant(0x2C, dl)
11761                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11762
11763     SDValue ThreadPointer =
11764         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11765                     false, false, 0);
11766
11767     SDValue res;
11768     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11769       res = ThreadPointer;
11770     } else {
11771       // Load the _tls_index variable
11772       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11773       if (Subtarget->is64Bit())
11774         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11775                              MachinePointerInfo(), MVT::i32, false, false,
11776                              false, 0);
11777       else
11778         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11779                           false, false, 0);
11780
11781       auto &DL = DAG.getDataLayout();
11782       SDValue Scale =
11783           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11784       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11785
11786       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11787     }
11788
11789     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11790                       false, 0);
11791
11792     // Get the offset of start of .tls section
11793     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11794                                              GA->getValueType(0),
11795                                              GA->getOffset(), X86II::MO_SECREL);
11796     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11797
11798     // The address of the thread local variable is the add of the thread
11799     // pointer with the offset of the variable.
11800     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11801   }
11802
11803   llvm_unreachable("TLS not implemented for this target.");
11804 }
11805
11806 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11807 /// and take a 2 x i32 value to shift plus a shift amount.
11808 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11809   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11810   MVT VT = Op.getSimpleValueType();
11811   unsigned VTBits = VT.getSizeInBits();
11812   SDLoc dl(Op);
11813   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11814   SDValue ShOpLo = Op.getOperand(0);
11815   SDValue ShOpHi = Op.getOperand(1);
11816   SDValue ShAmt  = Op.getOperand(2);
11817   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11818   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11819   // during isel.
11820   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11821                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11822   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11823                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11824                        : DAG.getConstant(0, dl, VT);
11825
11826   SDValue Tmp2, Tmp3;
11827   if (Op.getOpcode() == ISD::SHL_PARTS) {
11828     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11829     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11830   } else {
11831     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11832     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11833   }
11834
11835   // If the shift amount is larger or equal than the width of a part we can't
11836   // rely on the results of shld/shrd. Insert a test and select the appropriate
11837   // values for large shift amounts.
11838   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11839                                 DAG.getConstant(VTBits, dl, MVT::i8));
11840   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11841                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11842
11843   SDValue Hi, Lo;
11844   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11845   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11846   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11847
11848   if (Op.getOpcode() == ISD::SHL_PARTS) {
11849     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11850     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11851   } else {
11852     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11853     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11854   }
11855
11856   SDValue Ops[2] = { Lo, Hi };
11857   return DAG.getMergeValues(Ops, dl);
11858 }
11859
11860 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11861                                            SelectionDAG &DAG) const {
11862   SDValue Src = Op.getOperand(0);
11863   MVT SrcVT = Src.getSimpleValueType();
11864   MVT VT = Op.getSimpleValueType();
11865   SDLoc dl(Op);
11866
11867   if (SrcVT.isVector()) {
11868     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11869       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11870                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11871                          DAG.getUNDEF(SrcVT)));
11872     }
11873     if (SrcVT.getVectorElementType() == MVT::i1) {
11874       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11875       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11876                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11877     }
11878     return SDValue();
11879   }
11880
11881   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11882          "Unknown SINT_TO_FP to lower!");
11883
11884   // These are really Legal; return the operand so the caller accepts it as
11885   // Legal.
11886   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11887     return Op;
11888   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11889       Subtarget->is64Bit()) {
11890     return Op;
11891   }
11892
11893   unsigned Size = SrcVT.getSizeInBits()/8;
11894   MachineFunction &MF = DAG.getMachineFunction();
11895   auto PtrVT = getPointerTy(MF.getDataLayout());
11896   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11897   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11898   SDValue Chain = DAG.getStore(
11899       DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11900       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11901       false, 0);
11902   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11903 }
11904
11905 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11906                                      SDValue StackSlot,
11907                                      SelectionDAG &DAG) const {
11908   // Build the FILD
11909   SDLoc DL(Op);
11910   SDVTList Tys;
11911   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11912   if (useSSE)
11913     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11914   else
11915     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11916
11917   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11918
11919   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11920   MachineMemOperand *MMO;
11921   if (FI) {
11922     int SSFI = FI->getIndex();
11923     MMO = DAG.getMachineFunction().getMachineMemOperand(
11924         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11925         MachineMemOperand::MOLoad, ByteSize, ByteSize);
11926   } else {
11927     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11928     StackSlot = StackSlot.getOperand(1);
11929   }
11930   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11931   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11932                                            X86ISD::FILD, DL,
11933                                            Tys, Ops, SrcVT, MMO);
11934
11935   if (useSSE) {
11936     Chain = Result.getValue(1);
11937     SDValue InFlag = Result.getValue(2);
11938
11939     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11940     // shouldn't be necessary except that RFP cannot be live across
11941     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11942     MachineFunction &MF = DAG.getMachineFunction();
11943     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11944     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11945     auto PtrVT = getPointerTy(MF.getDataLayout());
11946     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11947     Tys = DAG.getVTList(MVT::Other);
11948     SDValue Ops[] = {
11949       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11950     };
11951     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11952         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11953         MachineMemOperand::MOStore, SSFISize, SSFISize);
11954
11955     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11956                                     Ops, Op.getValueType(), MMO);
11957     Result = DAG.getLoad(
11958         Op.getValueType(), DL, Chain, StackSlot,
11959         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11960         false, false, false, 0);
11961   }
11962
11963   return Result;
11964 }
11965
11966 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11967 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11968                                                SelectionDAG &DAG) const {
11969   // This algorithm is not obvious. Here it is what we're trying to output:
11970   /*
11971      movq       %rax,  %xmm0
11972      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11973      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11974      #ifdef __SSE3__
11975        haddpd   %xmm0, %xmm0
11976      #else
11977        pshufd   $0x4e, %xmm0, %xmm1
11978        addpd    %xmm1, %xmm0
11979      #endif
11980   */
11981
11982   SDLoc dl(Op);
11983   LLVMContext *Context = DAG.getContext();
11984
11985   // Build some magic constants.
11986   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11987   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11988   auto PtrVT = getPointerTy(DAG.getDataLayout());
11989   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11990
11991   SmallVector<Constant*,2> CV1;
11992   CV1.push_back(
11993     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11994                                       APInt(64, 0x4330000000000000ULL))));
11995   CV1.push_back(
11996     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11997                                       APInt(64, 0x4530000000000000ULL))));
11998   Constant *C1 = ConstantVector::get(CV1);
11999   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12000
12001   // Load the 64-bit value into an XMM register.
12002   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12003                             Op.getOperand(0));
12004   SDValue CLod0 =
12005       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12006                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12007                   false, false, false, 16);
12008   SDValue Unpck1 =
12009       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12010
12011   SDValue CLod1 =
12012       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12013                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12014                   false, false, false, 16);
12015   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12016   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12017   SDValue Result;
12018
12019   if (Subtarget->hasSSE3()) {
12020     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12021     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12022   } else {
12023     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12024     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12025                                            S2F, 0x4E, DAG);
12026     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12027                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12028   }
12029
12030   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12031                      DAG.getIntPtrConstant(0, dl));
12032 }
12033
12034 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12035 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12036                                                SelectionDAG &DAG) const {
12037   SDLoc dl(Op);
12038   // FP constant to bias correct the final result.
12039   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12040                                    MVT::f64);
12041
12042   // Load the 32-bit value into an XMM register.
12043   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12044                              Op.getOperand(0));
12045
12046   // Zero out the upper parts of the register.
12047   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12048
12049   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12050                      DAG.getBitcast(MVT::v2f64, Load),
12051                      DAG.getIntPtrConstant(0, dl));
12052
12053   // Or the load with the bias.
12054   SDValue Or = DAG.getNode(
12055       ISD::OR, dl, MVT::v2i64,
12056       DAG.getBitcast(MVT::v2i64,
12057                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12058       DAG.getBitcast(MVT::v2i64,
12059                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12060   Or =
12061       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12062                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12063
12064   // Subtract the bias.
12065   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12066
12067   // Handle final rounding.
12068   EVT DestVT = Op.getValueType();
12069
12070   if (DestVT.bitsLT(MVT::f64))
12071     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12072                        DAG.getIntPtrConstant(0, dl));
12073   if (DestVT.bitsGT(MVT::f64))
12074     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12075
12076   // Handle final rounding.
12077   return Sub;
12078 }
12079
12080 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12081                                      const X86Subtarget &Subtarget) {
12082   // The algorithm is the following:
12083   // #ifdef __SSE4_1__
12084   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12085   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12086   //                                 (uint4) 0x53000000, 0xaa);
12087   // #else
12088   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12089   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12090   // #endif
12091   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12092   //     return (float4) lo + fhi;
12093
12094   SDLoc DL(Op);
12095   SDValue V = Op->getOperand(0);
12096   EVT VecIntVT = V.getValueType();
12097   bool Is128 = VecIntVT == MVT::v4i32;
12098   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12099   // If we convert to something else than the supported type, e.g., to v4f64,
12100   // abort early.
12101   if (VecFloatVT != Op->getValueType(0))
12102     return SDValue();
12103
12104   unsigned NumElts = VecIntVT.getVectorNumElements();
12105   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12106          "Unsupported custom type");
12107   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12108
12109   // In the #idef/#else code, we have in common:
12110   // - The vector of constants:
12111   // -- 0x4b000000
12112   // -- 0x53000000
12113   // - A shift:
12114   // -- v >> 16
12115
12116   // Create the splat vector for 0x4b000000.
12117   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12118   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12119                            CstLow, CstLow, CstLow, CstLow};
12120   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12121                                   makeArrayRef(&CstLowArray[0], NumElts));
12122   // Create the splat vector for 0x53000000.
12123   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12124   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12125                             CstHigh, CstHigh, CstHigh, CstHigh};
12126   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12127                                    makeArrayRef(&CstHighArray[0], NumElts));
12128
12129   // Create the right shift.
12130   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12131   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12132                              CstShift, CstShift, CstShift, CstShift};
12133   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12134                                     makeArrayRef(&CstShiftArray[0], NumElts));
12135   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12136
12137   SDValue Low, High;
12138   if (Subtarget.hasSSE41()) {
12139     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12140     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12141     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12142     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12143     // Low will be bitcasted right away, so do not bother bitcasting back to its
12144     // original type.
12145     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12146                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12147     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12148     //                                 (uint4) 0x53000000, 0xaa);
12149     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12150     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12151     // High will be bitcasted right away, so do not bother bitcasting back to
12152     // its original type.
12153     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12154                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12155   } else {
12156     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12157     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12158                                      CstMask, CstMask, CstMask);
12159     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12160     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12161     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12162
12163     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12164     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12165   }
12166
12167   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12168   SDValue CstFAdd = DAG.getConstantFP(
12169       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12170   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12171                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12172   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12173                                    makeArrayRef(&CstFAddArray[0], NumElts));
12174
12175   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12176   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12177   SDValue FHigh =
12178       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12179   //     return (float4) lo + fhi;
12180   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12181   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12182 }
12183
12184 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12185                                                SelectionDAG &DAG) const {
12186   SDValue N0 = Op.getOperand(0);
12187   MVT SVT = N0.getSimpleValueType();
12188   SDLoc dl(Op);
12189
12190   switch (SVT.SimpleTy) {
12191   default:
12192     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12193   case MVT::v4i8:
12194   case MVT::v4i16:
12195   case MVT::v8i8:
12196   case MVT::v8i16: {
12197     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12198     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12199                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12200   }
12201   case MVT::v4i32:
12202   case MVT::v8i32:
12203     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12204   case MVT::v16i8:
12205   case MVT::v16i16:
12206     if (Subtarget->hasAVX512())
12207       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12208                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12209   }
12210   llvm_unreachable(nullptr);
12211 }
12212
12213 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12214                                            SelectionDAG &DAG) const {
12215   SDValue N0 = Op.getOperand(0);
12216   SDLoc dl(Op);
12217   auto PtrVT = getPointerTy(DAG.getDataLayout());
12218
12219   if (Op.getValueType().isVector())
12220     return lowerUINT_TO_FP_vec(Op, DAG);
12221
12222   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12223   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12224   // the optimization here.
12225   if (DAG.SignBitIsZero(N0))
12226     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12227
12228   MVT SrcVT = N0.getSimpleValueType();
12229   MVT DstVT = Op.getSimpleValueType();
12230   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12231     return LowerUINT_TO_FP_i64(Op, DAG);
12232   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12233     return LowerUINT_TO_FP_i32(Op, DAG);
12234   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12235     return SDValue();
12236
12237   // Make a 64-bit buffer, and use it to build an FILD.
12238   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12239   if (SrcVT == MVT::i32) {
12240     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12241     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12242     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12243                                   StackSlot, MachinePointerInfo(),
12244                                   false, false, 0);
12245     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12246                                   OffsetSlot, MachinePointerInfo(),
12247                                   false, false, 0);
12248     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12249     return Fild;
12250   }
12251
12252   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12253   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12254                                StackSlot, MachinePointerInfo(),
12255                                false, false, 0);
12256   // For i64 source, we need to add the appropriate power of 2 if the input
12257   // was negative.  This is the same as the optimization in
12258   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12259   // we must be careful to do the computation in x87 extended precision, not
12260   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12261   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12262   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12263       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12264       MachineMemOperand::MOLoad, 8, 8);
12265
12266   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12267   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12268   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12269                                          MVT::i64, MMO);
12270
12271   APInt FF(32, 0x5F800000ULL);
12272
12273   // Check whether the sign bit is set.
12274   SDValue SignSet = DAG.getSetCC(
12275       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12276       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12277
12278   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12279   SDValue FudgePtr = DAG.getConstantPool(
12280       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12281
12282   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12283   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12284   SDValue Four = DAG.getIntPtrConstant(4, dl);
12285   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12286                                Zero, Four);
12287   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12288
12289   // Load the value out, extending it from f32 to f80.
12290   // FIXME: Avoid the extend by constructing the right constant pool?
12291   SDValue Fudge = DAG.getExtLoad(
12292       ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12293       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12294       false, false, false, 4);
12295   // Extend everything to 80 bits to force it to be done on x87.
12296   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12297   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12298                      DAG.getIntPtrConstant(0, dl));
12299 }
12300
12301 std::pair<SDValue,SDValue>
12302 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12303                                     bool IsSigned, bool IsReplace) const {
12304   SDLoc DL(Op);
12305
12306   EVT DstTy = Op.getValueType();
12307   auto PtrVT = getPointerTy(DAG.getDataLayout());
12308
12309   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12310     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12311     DstTy = MVT::i64;
12312   }
12313
12314   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12315          DstTy.getSimpleVT() >= MVT::i16 &&
12316          "Unknown FP_TO_INT to lower!");
12317
12318   // These are really Legal.
12319   if (DstTy == MVT::i32 &&
12320       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12321     return std::make_pair(SDValue(), SDValue());
12322   if (Subtarget->is64Bit() &&
12323       DstTy == MVT::i64 &&
12324       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12325     return std::make_pair(SDValue(), SDValue());
12326
12327   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12328   // stack slot, or into the FTOL runtime function.
12329   MachineFunction &MF = DAG.getMachineFunction();
12330   unsigned MemSize = DstTy.getSizeInBits()/8;
12331   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12332   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12333
12334   unsigned Opc;
12335   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12336     Opc = X86ISD::WIN_FTOL;
12337   else
12338     switch (DstTy.getSimpleVT().SimpleTy) {
12339     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12340     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12341     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12342     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12343     }
12344
12345   SDValue Chain = DAG.getEntryNode();
12346   SDValue Value = Op.getOperand(0);
12347   EVT TheVT = Op.getOperand(0).getValueType();
12348   // FIXME This causes a redundant load/store if the SSE-class value is already
12349   // in memory, such as if it is on the callstack.
12350   if (isScalarFPTypeInSSEReg(TheVT)) {
12351     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12352     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12353                          MachinePointerInfo::getFixedStack(MF, SSFI), false,
12354                          false, 0);
12355     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12356     SDValue Ops[] = {
12357       Chain, StackSlot, DAG.getValueType(TheVT)
12358     };
12359
12360     MachineMemOperand *MMO =
12361         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12362                                 MachineMemOperand::MOLoad, MemSize, MemSize);
12363     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12364     Chain = Value.getValue(1);
12365     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12366     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12367   }
12368
12369   MachineMemOperand *MMO =
12370       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12371                               MachineMemOperand::MOStore, MemSize, MemSize);
12372
12373   if (Opc != X86ISD::WIN_FTOL) {
12374     // Build the FP_TO_INT*_IN_MEM
12375     SDValue Ops[] = { Chain, Value, StackSlot };
12376     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12377                                            Ops, DstTy, MMO);
12378     return std::make_pair(FIST, StackSlot);
12379   } else {
12380     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12381       DAG.getVTList(MVT::Other, MVT::Glue),
12382       Chain, Value);
12383     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12384       MVT::i32, ftol.getValue(1));
12385     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12386       MVT::i32, eax.getValue(2));
12387     SDValue Ops[] = { eax, edx };
12388     SDValue pair = IsReplace
12389       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12390       : DAG.getMergeValues(Ops, DL);
12391     return std::make_pair(pair, SDValue());
12392   }
12393 }
12394
12395 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12396                               const X86Subtarget *Subtarget) {
12397   MVT VT = Op->getSimpleValueType(0);
12398   SDValue In = Op->getOperand(0);
12399   MVT InVT = In.getSimpleValueType();
12400   SDLoc dl(Op);
12401
12402   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12403     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12404
12405   // Optimize vectors in AVX mode:
12406   //
12407   //   v8i16 -> v8i32
12408   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12409   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12410   //   Concat upper and lower parts.
12411   //
12412   //   v4i32 -> v4i64
12413   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12414   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12415   //   Concat upper and lower parts.
12416   //
12417
12418   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12419       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12420       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12421     return SDValue();
12422
12423   if (Subtarget->hasInt256())
12424     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12425
12426   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12427   SDValue Undef = DAG.getUNDEF(InVT);
12428   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12429   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12430   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12431
12432   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12433                              VT.getVectorNumElements()/2);
12434
12435   OpLo = DAG.getBitcast(HVT, OpLo);
12436   OpHi = DAG.getBitcast(HVT, OpHi);
12437
12438   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12439 }
12440
12441 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12442                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12443   MVT VT = Op->getSimpleValueType(0);
12444   SDValue In = Op->getOperand(0);
12445   MVT InVT = In.getSimpleValueType();
12446   SDLoc DL(Op);
12447   unsigned int NumElts = VT.getVectorNumElements();
12448   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12449     return SDValue();
12450
12451   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12452     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12453
12454   assert(InVT.getVectorElementType() == MVT::i1);
12455   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12456   SDValue One =
12457    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12458   SDValue Zero =
12459    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12460
12461   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12462   if (VT.is512BitVector())
12463     return V;
12464   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12465 }
12466
12467 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12468                                SelectionDAG &DAG) {
12469   if (Subtarget->hasFp256())
12470     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12471       return Res;
12472
12473   return SDValue();
12474 }
12475
12476 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12477                                 SelectionDAG &DAG) {
12478   SDLoc DL(Op);
12479   MVT VT = Op.getSimpleValueType();
12480   SDValue In = Op.getOperand(0);
12481   MVT SVT = In.getSimpleValueType();
12482
12483   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12484     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12485
12486   if (Subtarget->hasFp256())
12487     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12488       return Res;
12489
12490   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12491          VT.getVectorNumElements() != SVT.getVectorNumElements());
12492   return SDValue();
12493 }
12494
12495 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12496   SDLoc DL(Op);
12497   MVT VT = Op.getSimpleValueType();
12498   SDValue In = Op.getOperand(0);
12499   MVT InVT = In.getSimpleValueType();
12500
12501   if (VT == MVT::i1) {
12502     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12503            "Invalid scalar TRUNCATE operation");
12504     if (InVT.getSizeInBits() >= 32)
12505       return SDValue();
12506     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12507     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12508   }
12509   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12510          "Invalid TRUNCATE operation");
12511
12512   // move vector to mask - truncate solution for SKX
12513   if (VT.getVectorElementType() == MVT::i1) {
12514     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12515         Subtarget->hasBWI())
12516       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12517     if ((InVT.is256BitVector() || InVT.is128BitVector())
12518         && InVT.getScalarSizeInBits() <= 16 &&
12519         Subtarget->hasBWI() && Subtarget->hasVLX())
12520       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12521     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12522         Subtarget->hasDQI())
12523       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12524     if ((InVT.is256BitVector() || InVT.is128BitVector())
12525         && InVT.getScalarSizeInBits() >= 32 &&
12526         Subtarget->hasDQI() && Subtarget->hasVLX())
12527       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12528   }
12529
12530   if (VT.getVectorElementType() == MVT::i1) {
12531     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12532     unsigned NumElts = InVT.getVectorNumElements();
12533     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12534     if (InVT.getSizeInBits() < 512) {
12535       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12536       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12537       InVT = ExtVT;
12538     }
12539
12540     SDValue OneV =
12541      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12542     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12543     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12544   }
12545
12546   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12547   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12548       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12549     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12550
12551   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12552     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12553     if (Subtarget->hasInt256()) {
12554       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12555       In = DAG.getBitcast(MVT::v8i32, In);
12556       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12557                                 ShufMask);
12558       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12559                          DAG.getIntPtrConstant(0, DL));
12560     }
12561
12562     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12563                                DAG.getIntPtrConstant(0, DL));
12564     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12565                                DAG.getIntPtrConstant(2, DL));
12566     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12567     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12568     static const int ShufMask[] = {0, 2, 4, 6};
12569     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12570   }
12571
12572   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12573     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12574     if (Subtarget->hasInt256()) {
12575       In = DAG.getBitcast(MVT::v32i8, In);
12576
12577       SmallVector<SDValue,32> pshufbMask;
12578       for (unsigned i = 0; i < 2; ++i) {
12579         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12580         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12581         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12582         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12583         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12584         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12585         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12586         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12587         for (unsigned j = 0; j < 8; ++j)
12588           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12589       }
12590       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12591       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12592       In = DAG.getBitcast(MVT::v4i64, In);
12593
12594       static const int ShufMask[] = {0,  2,  -1,  -1};
12595       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12596                                 &ShufMask[0]);
12597       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12598                        DAG.getIntPtrConstant(0, DL));
12599       return DAG.getBitcast(VT, In);
12600     }
12601
12602     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12603                                DAG.getIntPtrConstant(0, DL));
12604
12605     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12606                                DAG.getIntPtrConstant(4, DL));
12607
12608     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12609     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12610
12611     // The PSHUFB mask:
12612     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12613                                    -1, -1, -1, -1, -1, -1, -1, -1};
12614
12615     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12616     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12617     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12618
12619     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12620     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12621
12622     // The MOVLHPS Mask:
12623     static const int ShufMask2[] = {0, 1, 4, 5};
12624     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12625     return DAG.getBitcast(MVT::v8i16, res);
12626   }
12627
12628   // Handle truncation of V256 to V128 using shuffles.
12629   if (!VT.is128BitVector() || !InVT.is256BitVector())
12630     return SDValue();
12631
12632   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12633
12634   unsigned NumElems = VT.getVectorNumElements();
12635   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12636
12637   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12638   // Prepare truncation shuffle mask
12639   for (unsigned i = 0; i != NumElems; ++i)
12640     MaskVec[i] = i * 2;
12641   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12642                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12643   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12644                      DAG.getIntPtrConstant(0, DL));
12645 }
12646
12647 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12648                                            SelectionDAG &DAG) const {
12649   assert(!Op.getSimpleValueType().isVector());
12650
12651   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12652     /*IsSigned=*/ true, /*IsReplace=*/ false);
12653   SDValue FIST = Vals.first, StackSlot = Vals.second;
12654   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12655   if (!FIST.getNode()) return Op;
12656
12657   if (StackSlot.getNode())
12658     // Load the result.
12659     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12660                        FIST, StackSlot, MachinePointerInfo(),
12661                        false, false, false, 0);
12662
12663   // The node is the result.
12664   return FIST;
12665 }
12666
12667 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12668                                            SelectionDAG &DAG) const {
12669   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12670     /*IsSigned=*/ false, /*IsReplace=*/ false);
12671   SDValue FIST = Vals.first, StackSlot = Vals.second;
12672   assert(FIST.getNode() && "Unexpected failure");
12673
12674   if (StackSlot.getNode())
12675     // Load the result.
12676     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12677                        FIST, StackSlot, MachinePointerInfo(),
12678                        false, false, false, 0);
12679
12680   // The node is the result.
12681   return FIST;
12682 }
12683
12684 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12685   SDLoc DL(Op);
12686   MVT VT = Op.getSimpleValueType();
12687   SDValue In = Op.getOperand(0);
12688   MVT SVT = In.getSimpleValueType();
12689
12690   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12691
12692   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12693                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12694                                  In, DAG.getUNDEF(SVT)));
12695 }
12696
12697 /// The only differences between FABS and FNEG are the mask and the logic op.
12698 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12699 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12700   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12701          "Wrong opcode for lowering FABS or FNEG.");
12702
12703   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12704
12705   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12706   // into an FNABS. We'll lower the FABS after that if it is still in use.
12707   if (IsFABS)
12708     for (SDNode *User : Op->uses())
12709       if (User->getOpcode() == ISD::FNEG)
12710         return Op;
12711
12712   SDLoc dl(Op);
12713   MVT VT = Op.getSimpleValueType();
12714
12715   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12716   // decide if we should generate a 16-byte constant mask when we only need 4 or
12717   // 8 bytes for the scalar case.
12718
12719   MVT LogicVT;
12720   MVT EltVT;
12721   unsigned NumElts;
12722
12723   if (VT.isVector()) {
12724     LogicVT = VT;
12725     EltVT = VT.getVectorElementType();
12726     NumElts = VT.getVectorNumElements();
12727   } else {
12728     // There are no scalar bitwise logical SSE/AVX instructions, so we
12729     // generate a 16-byte vector constant and logic op even for the scalar case.
12730     // Using a 16-byte mask allows folding the load of the mask with
12731     // the logic op, so it can save (~4 bytes) on code size.
12732     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12733     EltVT = VT;
12734     NumElts = (VT == MVT::f64) ? 2 : 4;
12735   }
12736
12737   unsigned EltBits = EltVT.getSizeInBits();
12738   LLVMContext *Context = DAG.getContext();
12739   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12740   APInt MaskElt =
12741     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12742   Constant *C = ConstantInt::get(*Context, MaskElt);
12743   C = ConstantVector::getSplat(NumElts, C);
12744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12745   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12746   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12747   SDValue Mask =
12748       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12749                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12750                   false, false, false, Alignment);
12751
12752   SDValue Op0 = Op.getOperand(0);
12753   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12754   unsigned LogicOp =
12755     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12756   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12757
12758   if (VT.isVector())
12759     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12760
12761   // For the scalar case extend to a 128-bit vector, perform the logic op,
12762   // and extract the scalar result back out.
12763   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12764   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12765   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12766                      DAG.getIntPtrConstant(0, dl));
12767 }
12768
12769 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12771   LLVMContext *Context = DAG.getContext();
12772   SDValue Op0 = Op.getOperand(0);
12773   SDValue Op1 = Op.getOperand(1);
12774   SDLoc dl(Op);
12775   MVT VT = Op.getSimpleValueType();
12776   MVT SrcVT = Op1.getSimpleValueType();
12777
12778   // If second operand is smaller, extend it first.
12779   if (SrcVT.bitsLT(VT)) {
12780     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12781     SrcVT = VT;
12782   }
12783   // And if it is bigger, shrink it first.
12784   if (SrcVT.bitsGT(VT)) {
12785     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12786     SrcVT = VT;
12787   }
12788
12789   // At this point the operands and the result should have the same
12790   // type, and that won't be f80 since that is not custom lowered.
12791
12792   const fltSemantics &Sem =
12793       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12794   const unsigned SizeInBits = VT.getSizeInBits();
12795
12796   SmallVector<Constant *, 4> CV(
12797       VT == MVT::f64 ? 2 : 4,
12798       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12799
12800   // First, clear all bits but the sign bit from the second operand (sign).
12801   CV[0] = ConstantFP::get(*Context,
12802                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12803   Constant *C = ConstantVector::get(CV);
12804   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12805   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12806
12807   // Perform all logic operations as 16-byte vectors because there are no
12808   // scalar FP logic instructions in SSE. This allows load folding of the
12809   // constants into the logic instructions.
12810   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12811   SDValue Mask1 =
12812       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12813                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12814                   false, false, false, 16);
12815   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12816   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12817
12818   // Next, clear the sign bit from the first operand (magnitude).
12819   // If it's a constant, we can clear it here.
12820   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12821     APFloat APF = Op0CN->getValueAPF();
12822     // If the magnitude is a positive zero, the sign bit alone is enough.
12823     if (APF.isPosZero())
12824       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12825                          DAG.getIntPtrConstant(0, dl));
12826     APF.clearSign();
12827     CV[0] = ConstantFP::get(*Context, APF);
12828   } else {
12829     CV[0] = ConstantFP::get(
12830         *Context,
12831         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12832   }
12833   C = ConstantVector::get(CV);
12834   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12835   SDValue Val =
12836       DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12837                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12838                   false, false, false, 16);
12839   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12840   if (!isa<ConstantFPSDNode>(Op0)) {
12841     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12842     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12843   }
12844   // OR the magnitude value with the sign bit.
12845   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12846   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12847                      DAG.getIntPtrConstant(0, dl));
12848 }
12849
12850 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12851   SDValue N0 = Op.getOperand(0);
12852   SDLoc dl(Op);
12853   MVT VT = Op.getSimpleValueType();
12854
12855   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12856   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12857                                   DAG.getConstant(1, dl, VT));
12858   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12859 }
12860
12861 // Check whether an OR'd tree is PTEST-able.
12862 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12863                                       SelectionDAG &DAG) {
12864   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12865
12866   if (!Subtarget->hasSSE41())
12867     return SDValue();
12868
12869   if (!Op->hasOneUse())
12870     return SDValue();
12871
12872   SDNode *N = Op.getNode();
12873   SDLoc DL(N);
12874
12875   SmallVector<SDValue, 8> Opnds;
12876   DenseMap<SDValue, unsigned> VecInMap;
12877   SmallVector<SDValue, 8> VecIns;
12878   EVT VT = MVT::Other;
12879
12880   // Recognize a special case where a vector is casted into wide integer to
12881   // test all 0s.
12882   Opnds.push_back(N->getOperand(0));
12883   Opnds.push_back(N->getOperand(1));
12884
12885   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12886     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12887     // BFS traverse all OR'd operands.
12888     if (I->getOpcode() == ISD::OR) {
12889       Opnds.push_back(I->getOperand(0));
12890       Opnds.push_back(I->getOperand(1));
12891       // Re-evaluate the number of nodes to be traversed.
12892       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12893       continue;
12894     }
12895
12896     // Quit if a non-EXTRACT_VECTOR_ELT
12897     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12898       return SDValue();
12899
12900     // Quit if without a constant index.
12901     SDValue Idx = I->getOperand(1);
12902     if (!isa<ConstantSDNode>(Idx))
12903       return SDValue();
12904
12905     SDValue ExtractedFromVec = I->getOperand(0);
12906     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12907     if (M == VecInMap.end()) {
12908       VT = ExtractedFromVec.getValueType();
12909       // Quit if not 128/256-bit vector.
12910       if (!VT.is128BitVector() && !VT.is256BitVector())
12911         return SDValue();
12912       // Quit if not the same type.
12913       if (VecInMap.begin() != VecInMap.end() &&
12914           VT != VecInMap.begin()->first.getValueType())
12915         return SDValue();
12916       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12917       VecIns.push_back(ExtractedFromVec);
12918     }
12919     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12920   }
12921
12922   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12923          "Not extracted from 128-/256-bit vector.");
12924
12925   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12926
12927   for (DenseMap<SDValue, unsigned>::const_iterator
12928         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12929     // Quit if not all elements are used.
12930     if (I->second != FullMask)
12931       return SDValue();
12932   }
12933
12934   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12935
12936   // Cast all vectors into TestVT for PTEST.
12937   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12938     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12939
12940   // If more than one full vectors are evaluated, OR them first before PTEST.
12941   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12942     // Each iteration will OR 2 nodes and append the result until there is only
12943     // 1 node left, i.e. the final OR'd value of all vectors.
12944     SDValue LHS = VecIns[Slot];
12945     SDValue RHS = VecIns[Slot + 1];
12946     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12947   }
12948
12949   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12950                      VecIns.back(), VecIns.back());
12951 }
12952
12953 /// \brief return true if \c Op has a use that doesn't just read flags.
12954 static bool hasNonFlagsUse(SDValue Op) {
12955   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12956        ++UI) {
12957     SDNode *User = *UI;
12958     unsigned UOpNo = UI.getOperandNo();
12959     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12960       // Look pass truncate.
12961       UOpNo = User->use_begin().getOperandNo();
12962       User = *User->use_begin();
12963     }
12964
12965     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12966         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12967       return true;
12968   }
12969   return false;
12970 }
12971
12972 /// Emit nodes that will be selected as "test Op0,Op0", or something
12973 /// equivalent.
12974 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12975                                     SelectionDAG &DAG) const {
12976   if (Op.getValueType() == MVT::i1) {
12977     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12978     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12979                        DAG.getConstant(0, dl, MVT::i8));
12980   }
12981   // CF and OF aren't always set the way we want. Determine which
12982   // of these we need.
12983   bool NeedCF = false;
12984   bool NeedOF = false;
12985   switch (X86CC) {
12986   default: break;
12987   case X86::COND_A: case X86::COND_AE:
12988   case X86::COND_B: case X86::COND_BE:
12989     NeedCF = true;
12990     break;
12991   case X86::COND_G: case X86::COND_GE:
12992   case X86::COND_L: case X86::COND_LE:
12993   case X86::COND_O: case X86::COND_NO: {
12994     // Check if we really need to set the
12995     // Overflow flag. If NoSignedWrap is present
12996     // that is not actually needed.
12997     switch (Op->getOpcode()) {
12998     case ISD::ADD:
12999     case ISD::SUB:
13000     case ISD::MUL:
13001     case ISD::SHL: {
13002       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13003       if (BinNode->Flags.hasNoSignedWrap())
13004         break;
13005     }
13006     default:
13007       NeedOF = true;
13008       break;
13009     }
13010     break;
13011   }
13012   }
13013   // See if we can use the EFLAGS value from the operand instead of
13014   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13015   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13016   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13017     // Emit a CMP with 0, which is the TEST pattern.
13018     //if (Op.getValueType() == MVT::i1)
13019     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13020     //                     DAG.getConstant(0, MVT::i1));
13021     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13022                        DAG.getConstant(0, dl, Op.getValueType()));
13023   }
13024   unsigned Opcode = 0;
13025   unsigned NumOperands = 0;
13026
13027   // Truncate operations may prevent the merge of the SETCC instruction
13028   // and the arithmetic instruction before it. Attempt to truncate the operands
13029   // of the arithmetic instruction and use a reduced bit-width instruction.
13030   bool NeedTruncation = false;
13031   SDValue ArithOp = Op;
13032   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13033     SDValue Arith = Op->getOperand(0);
13034     // Both the trunc and the arithmetic op need to have one user each.
13035     if (Arith->hasOneUse())
13036       switch (Arith.getOpcode()) {
13037         default: break;
13038         case ISD::ADD:
13039         case ISD::SUB:
13040         case ISD::AND:
13041         case ISD::OR:
13042         case ISD::XOR: {
13043           NeedTruncation = true;
13044           ArithOp = Arith;
13045         }
13046       }
13047   }
13048
13049   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13050   // which may be the result of a CAST.  We use the variable 'Op', which is the
13051   // non-casted variable when we check for possible users.
13052   switch (ArithOp.getOpcode()) {
13053   case ISD::ADD:
13054     // Due to an isel shortcoming, be conservative if this add is likely to be
13055     // selected as part of a load-modify-store instruction. When the root node
13056     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13057     // uses of other nodes in the match, such as the ADD in this case. This
13058     // leads to the ADD being left around and reselected, with the result being
13059     // two adds in the output.  Alas, even if none our users are stores, that
13060     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13061     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13062     // climbing the DAG back to the root, and it doesn't seem to be worth the
13063     // effort.
13064     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13065          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13066       if (UI->getOpcode() != ISD::CopyToReg &&
13067           UI->getOpcode() != ISD::SETCC &&
13068           UI->getOpcode() != ISD::STORE)
13069         goto default_case;
13070
13071     if (ConstantSDNode *C =
13072         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13073       // An add of one will be selected as an INC.
13074       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13075         Opcode = X86ISD::INC;
13076         NumOperands = 1;
13077         break;
13078       }
13079
13080       // An add of negative one (subtract of one) will be selected as a DEC.
13081       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13082         Opcode = X86ISD::DEC;
13083         NumOperands = 1;
13084         break;
13085       }
13086     }
13087
13088     // Otherwise use a regular EFLAGS-setting add.
13089     Opcode = X86ISD::ADD;
13090     NumOperands = 2;
13091     break;
13092   case ISD::SHL:
13093   case ISD::SRL:
13094     // If we have a constant logical shift that's only used in a comparison
13095     // against zero turn it into an equivalent AND. This allows turning it into
13096     // a TEST instruction later.
13097     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13098         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13099       EVT VT = Op.getValueType();
13100       unsigned BitWidth = VT.getSizeInBits();
13101       unsigned ShAmt = Op->getConstantOperandVal(1);
13102       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13103         break;
13104       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13105                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13106                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13107       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13108         break;
13109       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13110                                 DAG.getConstant(Mask, dl, VT));
13111       DAG.ReplaceAllUsesWith(Op, New);
13112       Op = New;
13113     }
13114     break;
13115
13116   case ISD::AND:
13117     // If the primary and result isn't used, don't bother using X86ISD::AND,
13118     // because a TEST instruction will be better.
13119     if (!hasNonFlagsUse(Op))
13120       break;
13121     // FALL THROUGH
13122   case ISD::SUB:
13123   case ISD::OR:
13124   case ISD::XOR:
13125     // Due to the ISEL shortcoming noted above, be conservative if this op is
13126     // likely to be selected as part of a load-modify-store instruction.
13127     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13128            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13129       if (UI->getOpcode() == ISD::STORE)
13130         goto default_case;
13131
13132     // Otherwise use a regular EFLAGS-setting instruction.
13133     switch (ArithOp.getOpcode()) {
13134     default: llvm_unreachable("unexpected operator!");
13135     case ISD::SUB: Opcode = X86ISD::SUB; break;
13136     case ISD::XOR: Opcode = X86ISD::XOR; break;
13137     case ISD::AND: Opcode = X86ISD::AND; break;
13138     case ISD::OR: {
13139       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13140         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13141         if (EFLAGS.getNode())
13142           return EFLAGS;
13143       }
13144       Opcode = X86ISD::OR;
13145       break;
13146     }
13147     }
13148
13149     NumOperands = 2;
13150     break;
13151   case X86ISD::ADD:
13152   case X86ISD::SUB:
13153   case X86ISD::INC:
13154   case X86ISD::DEC:
13155   case X86ISD::OR:
13156   case X86ISD::XOR:
13157   case X86ISD::AND:
13158     return SDValue(Op.getNode(), 1);
13159   default:
13160   default_case:
13161     break;
13162   }
13163
13164   // If we found that truncation is beneficial, perform the truncation and
13165   // update 'Op'.
13166   if (NeedTruncation) {
13167     EVT VT = Op.getValueType();
13168     SDValue WideVal = Op->getOperand(0);
13169     EVT WideVT = WideVal.getValueType();
13170     unsigned ConvertedOp = 0;
13171     // Use a target machine opcode to prevent further DAGCombine
13172     // optimizations that may separate the arithmetic operations
13173     // from the setcc node.
13174     switch (WideVal.getOpcode()) {
13175       default: break;
13176       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13177       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13178       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13179       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13180       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13181     }
13182
13183     if (ConvertedOp) {
13184       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13185       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13186         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13187         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13188         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13189       }
13190     }
13191   }
13192
13193   if (Opcode == 0)
13194     // Emit a CMP with 0, which is the TEST pattern.
13195     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13196                        DAG.getConstant(0, dl, Op.getValueType()));
13197
13198   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13199   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13200
13201   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13202   DAG.ReplaceAllUsesWith(Op, New);
13203   return SDValue(New.getNode(), 1);
13204 }
13205
13206 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13207 /// equivalent.
13208 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13209                                    SDLoc dl, SelectionDAG &DAG) const {
13210   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13211     if (C->getAPIntValue() == 0)
13212       return EmitTest(Op0, X86CC, dl, DAG);
13213
13214      if (Op0.getValueType() == MVT::i1)
13215        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13216   }
13217
13218   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13219        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13220     // Do the comparison at i32 if it's smaller, besides the Atom case.
13221     // This avoids subregister aliasing issues. Keep the smaller reference
13222     // if we're optimizing for size, however, as that'll allow better folding
13223     // of memory operations.
13224     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13225         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13226         !Subtarget->isAtom()) {
13227       unsigned ExtendOp =
13228           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13229       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13230       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13231     }
13232     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13233     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13234     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13235                               Op0, Op1);
13236     return SDValue(Sub.getNode(), 1);
13237   }
13238   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13239 }
13240
13241 /// Convert a comparison if required by the subtarget.
13242 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13243                                                  SelectionDAG &DAG) const {
13244   // If the subtarget does not support the FUCOMI instruction, floating-point
13245   // comparisons have to be converted.
13246   if (Subtarget->hasCMov() ||
13247       Cmp.getOpcode() != X86ISD::CMP ||
13248       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13249       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13250     return Cmp;
13251
13252   // The instruction selector will select an FUCOM instruction instead of
13253   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13254   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13255   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13256   SDLoc dl(Cmp);
13257   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13258   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13259   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13260                             DAG.getConstant(8, dl, MVT::i8));
13261   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13262   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13263 }
13264
13265 /// The minimum architected relative accuracy is 2^-12. We need one
13266 /// Newton-Raphson step to have a good float result (24 bits of precision).
13267 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13268                                             DAGCombinerInfo &DCI,
13269                                             unsigned &RefinementSteps,
13270                                             bool &UseOneConstNR) const {
13271   EVT VT = Op.getValueType();
13272   const char *RecipOp;
13273
13274   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13275   // TODO: Add support for AVX512 (v16f32).
13276   // It is likely not profitable to do this for f64 because a double-precision
13277   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13278   // instructions: convert to single, rsqrtss, convert back to double, refine
13279   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13280   // along with FMA, this could be a throughput win.
13281   if (VT == MVT::f32 && Subtarget->hasSSE1())
13282     RecipOp = "sqrtf";
13283   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13284            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13285     RecipOp = "vec-sqrtf";
13286   else
13287     return SDValue();
13288
13289   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13290   if (!Recips.isEnabled(RecipOp))
13291     return SDValue();
13292
13293   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13294   UseOneConstNR = false;
13295   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13296 }
13297
13298 /// The minimum architected relative accuracy is 2^-12. We need one
13299 /// Newton-Raphson step to have a good float result (24 bits of precision).
13300 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13301                                             DAGCombinerInfo &DCI,
13302                                             unsigned &RefinementSteps) const {
13303   EVT VT = Op.getValueType();
13304   const char *RecipOp;
13305
13306   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13307   // TODO: Add support for AVX512 (v16f32).
13308   // It is likely not profitable to do this for f64 because a double-precision
13309   // reciprocal estimate with refinement on x86 prior to FMA requires
13310   // 15 instructions: convert to single, rcpss, convert back to double, refine
13311   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13312   // along with FMA, this could be a throughput win.
13313   if (VT == MVT::f32 && Subtarget->hasSSE1())
13314     RecipOp = "divf";
13315   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13316            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13317     RecipOp = "vec-divf";
13318   else
13319     return SDValue();
13320
13321   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13322   if (!Recips.isEnabled(RecipOp))
13323     return SDValue();
13324
13325   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13326   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13327 }
13328
13329 /// If we have at least two divisions that use the same divisor, convert to
13330 /// multplication by a reciprocal. This may need to be adjusted for a given
13331 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13332 /// This is because we still need one division to calculate the reciprocal and
13333 /// then we need two multiplies by that reciprocal as replacements for the
13334 /// original divisions.
13335 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13336   return 2;
13337 }
13338
13339 static bool isAllOnes(SDValue V) {
13340   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13341   return C && C->isAllOnesValue();
13342 }
13343
13344 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13345 /// if it's possible.
13346 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13347                                      SDLoc dl, SelectionDAG &DAG) const {
13348   SDValue Op0 = And.getOperand(0);
13349   SDValue Op1 = And.getOperand(1);
13350   if (Op0.getOpcode() == ISD::TRUNCATE)
13351     Op0 = Op0.getOperand(0);
13352   if (Op1.getOpcode() == ISD::TRUNCATE)
13353     Op1 = Op1.getOperand(0);
13354
13355   SDValue LHS, RHS;
13356   if (Op1.getOpcode() == ISD::SHL)
13357     std::swap(Op0, Op1);
13358   if (Op0.getOpcode() == ISD::SHL) {
13359     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13360       if (And00C->getZExtValue() == 1) {
13361         // If we looked past a truncate, check that it's only truncating away
13362         // known zeros.
13363         unsigned BitWidth = Op0.getValueSizeInBits();
13364         unsigned AndBitWidth = And.getValueSizeInBits();
13365         if (BitWidth > AndBitWidth) {
13366           APInt Zeros, Ones;
13367           DAG.computeKnownBits(Op0, Zeros, Ones);
13368           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13369             return SDValue();
13370         }
13371         LHS = Op1;
13372         RHS = Op0.getOperand(1);
13373       }
13374   } else if (Op1.getOpcode() == ISD::Constant) {
13375     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13376     uint64_t AndRHSVal = AndRHS->getZExtValue();
13377     SDValue AndLHS = Op0;
13378
13379     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13380       LHS = AndLHS.getOperand(0);
13381       RHS = AndLHS.getOperand(1);
13382     }
13383
13384     // Use BT if the immediate can't be encoded in a TEST instruction.
13385     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13386       LHS = AndLHS;
13387       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13388     }
13389   }
13390
13391   if (LHS.getNode()) {
13392     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13393     // instruction.  Since the shift amount is in-range-or-undefined, we know
13394     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13395     // the encoding for the i16 version is larger than the i32 version.
13396     // Also promote i16 to i32 for performance / code size reason.
13397     if (LHS.getValueType() == MVT::i8 ||
13398         LHS.getValueType() == MVT::i16)
13399       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13400
13401     // If the operand types disagree, extend the shift amount to match.  Since
13402     // BT ignores high bits (like shifts) we can use anyextend.
13403     if (LHS.getValueType() != RHS.getValueType())
13404       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13405
13406     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13407     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13408     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13409                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13410   }
13411
13412   return SDValue();
13413 }
13414
13415 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13416 /// mask CMPs.
13417 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13418                               SDValue &Op1) {
13419   unsigned SSECC;
13420   bool Swap = false;
13421
13422   // SSE Condition code mapping:
13423   //  0 - EQ
13424   //  1 - LT
13425   //  2 - LE
13426   //  3 - UNORD
13427   //  4 - NEQ
13428   //  5 - NLT
13429   //  6 - NLE
13430   //  7 - ORD
13431   switch (SetCCOpcode) {
13432   default: llvm_unreachable("Unexpected SETCC condition");
13433   case ISD::SETOEQ:
13434   case ISD::SETEQ:  SSECC = 0; break;
13435   case ISD::SETOGT:
13436   case ISD::SETGT:  Swap = true; // Fallthrough
13437   case ISD::SETLT:
13438   case ISD::SETOLT: SSECC = 1; break;
13439   case ISD::SETOGE:
13440   case ISD::SETGE:  Swap = true; // Fallthrough
13441   case ISD::SETLE:
13442   case ISD::SETOLE: SSECC = 2; break;
13443   case ISD::SETUO:  SSECC = 3; break;
13444   case ISD::SETUNE:
13445   case ISD::SETNE:  SSECC = 4; break;
13446   case ISD::SETULE: Swap = true; // Fallthrough
13447   case ISD::SETUGE: SSECC = 5; break;
13448   case ISD::SETULT: Swap = true; // Fallthrough
13449   case ISD::SETUGT: SSECC = 6; break;
13450   case ISD::SETO:   SSECC = 7; break;
13451   case ISD::SETUEQ:
13452   case ISD::SETONE: SSECC = 8; break;
13453   }
13454   if (Swap)
13455     std::swap(Op0, Op1);
13456
13457   return SSECC;
13458 }
13459
13460 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13461 // ones, and then concatenate the result back.
13462 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13463   MVT VT = Op.getSimpleValueType();
13464
13465   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13466          "Unsupported value type for operation");
13467
13468   unsigned NumElems = VT.getVectorNumElements();
13469   SDLoc dl(Op);
13470   SDValue CC = Op.getOperand(2);
13471
13472   // Extract the LHS vectors
13473   SDValue LHS = Op.getOperand(0);
13474   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13475   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13476
13477   // Extract the RHS vectors
13478   SDValue RHS = Op.getOperand(1);
13479   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13480   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13481
13482   // Issue the operation on the smaller types and concatenate the result back
13483   MVT EltVT = VT.getVectorElementType();
13484   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13485   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13486                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13487                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13488 }
13489
13490 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13491   SDValue Op0 = Op.getOperand(0);
13492   SDValue Op1 = Op.getOperand(1);
13493   SDValue CC = Op.getOperand(2);
13494   MVT VT = Op.getSimpleValueType();
13495   SDLoc dl(Op);
13496
13497   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13498          "Unexpected type for boolean compare operation");
13499   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13500   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13501                                DAG.getConstant(-1, dl, VT));
13502   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13503                                DAG.getConstant(-1, dl, VT));
13504   switch (SetCCOpcode) {
13505   default: llvm_unreachable("Unexpected SETCC condition");
13506   case ISD::SETEQ:
13507     // (x == y) -> ~(x ^ y)
13508     return DAG.getNode(ISD::XOR, dl, VT,
13509                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13510                        DAG.getConstant(-1, dl, VT));
13511   case ISD::SETNE:
13512     // (x != y) -> (x ^ y)
13513     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13514   case ISD::SETUGT:
13515   case ISD::SETGT:
13516     // (x > y) -> (x & ~y)
13517     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13518   case ISD::SETULT:
13519   case ISD::SETLT:
13520     // (x < y) -> (~x & y)
13521     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13522   case ISD::SETULE:
13523   case ISD::SETLE:
13524     // (x <= y) -> (~x | y)
13525     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13526   case ISD::SETUGE:
13527   case ISD::SETGE:
13528     // (x >=y) -> (x | ~y)
13529     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13530   }
13531 }
13532
13533 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13534                                      const X86Subtarget *Subtarget) {
13535   SDValue Op0 = Op.getOperand(0);
13536   SDValue Op1 = Op.getOperand(1);
13537   SDValue CC = Op.getOperand(2);
13538   MVT VT = Op.getSimpleValueType();
13539   SDLoc dl(Op);
13540
13541   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13542          Op.getValueType().getScalarType() == MVT::i1 &&
13543          "Cannot set masked compare for this operation");
13544
13545   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13546   unsigned  Opc = 0;
13547   bool Unsigned = false;
13548   bool Swap = false;
13549   unsigned SSECC;
13550   switch (SetCCOpcode) {
13551   default: llvm_unreachable("Unexpected SETCC condition");
13552   case ISD::SETNE:  SSECC = 4; break;
13553   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13554   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13555   case ISD::SETLT:  Swap = true; //fall-through
13556   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13557   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13558   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13559   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13560   case ISD::SETULE: Unsigned = true; //fall-through
13561   case ISD::SETLE:  SSECC = 2; break;
13562   }
13563
13564   if (Swap)
13565     std::swap(Op0, Op1);
13566   if (Opc)
13567     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13568   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13569   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13570                      DAG.getConstant(SSECC, dl, MVT::i8));
13571 }
13572
13573 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13574 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13575 /// return an empty value.
13576 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13577 {
13578   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13579   if (!BV)
13580     return SDValue();
13581
13582   MVT VT = Op1.getSimpleValueType();
13583   MVT EVT = VT.getVectorElementType();
13584   unsigned n = VT.getVectorNumElements();
13585   SmallVector<SDValue, 8> ULTOp1;
13586
13587   for (unsigned i = 0; i < n; ++i) {
13588     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13589     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13590       return SDValue();
13591
13592     // Avoid underflow.
13593     APInt Val = Elt->getAPIntValue();
13594     if (Val == 0)
13595       return SDValue();
13596
13597     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13598   }
13599
13600   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13601 }
13602
13603 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13604                            SelectionDAG &DAG) {
13605   SDValue Op0 = Op.getOperand(0);
13606   SDValue Op1 = Op.getOperand(1);
13607   SDValue CC = Op.getOperand(2);
13608   MVT VT = Op.getSimpleValueType();
13609   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13610   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13611   SDLoc dl(Op);
13612
13613   if (isFP) {
13614 #ifndef NDEBUG
13615     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13616     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13617 #endif
13618
13619     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13620     unsigned Opc = X86ISD::CMPP;
13621     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13622       assert(VT.getVectorNumElements() <= 16);
13623       Opc = X86ISD::CMPM;
13624     }
13625     // In the two special cases we can't handle, emit two comparisons.
13626     if (SSECC == 8) {
13627       unsigned CC0, CC1;
13628       unsigned CombineOpc;
13629       if (SetCCOpcode == ISD::SETUEQ) {
13630         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13631       } else {
13632         assert(SetCCOpcode == ISD::SETONE);
13633         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13634       }
13635
13636       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13637                                  DAG.getConstant(CC0, dl, MVT::i8));
13638       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13639                                  DAG.getConstant(CC1, dl, MVT::i8));
13640       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13641     }
13642     // Handle all other FP comparisons here.
13643     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13644                        DAG.getConstant(SSECC, dl, MVT::i8));
13645   }
13646
13647   // Break 256-bit integer vector compare into smaller ones.
13648   if (VT.is256BitVector() && !Subtarget->hasInt256())
13649     return Lower256IntVSETCC(Op, DAG);
13650
13651   EVT OpVT = Op1.getValueType();
13652   if (OpVT.getVectorElementType() == MVT::i1)
13653     return LowerBoolVSETCC_AVX512(Op, DAG);
13654
13655   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13656   if (Subtarget->hasAVX512()) {
13657     if (Op1.getValueType().is512BitVector() ||
13658         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13659         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13660       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13661
13662     // In AVX-512 architecture setcc returns mask with i1 elements,
13663     // But there is no compare instruction for i8 and i16 elements in KNL.
13664     // We are not talking about 512-bit operands in this case, these
13665     // types are illegal.
13666     if (MaskResult &&
13667         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13668          OpVT.getVectorElementType().getSizeInBits() >= 8))
13669       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13670                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13671   }
13672
13673   // We are handling one of the integer comparisons here.  Since SSE only has
13674   // GT and EQ comparisons for integer, swapping operands and multiple
13675   // operations may be required for some comparisons.
13676   unsigned Opc;
13677   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13678   bool Subus = false;
13679
13680   switch (SetCCOpcode) {
13681   default: llvm_unreachable("Unexpected SETCC condition");
13682   case ISD::SETNE:  Invert = true;
13683   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13684   case ISD::SETLT:  Swap = true;
13685   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13686   case ISD::SETGE:  Swap = true;
13687   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13688                     Invert = true; break;
13689   case ISD::SETULT: Swap = true;
13690   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13691                     FlipSigns = true; break;
13692   case ISD::SETUGE: Swap = true;
13693   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13694                     FlipSigns = true; Invert = true; break;
13695   }
13696
13697   // Special case: Use min/max operations for SETULE/SETUGE
13698   MVT VET = VT.getVectorElementType();
13699   bool hasMinMax =
13700        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13701     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13702
13703   if (hasMinMax) {
13704     switch (SetCCOpcode) {
13705     default: break;
13706     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13707     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13708     }
13709
13710     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13711   }
13712
13713   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13714   if (!MinMax && hasSubus) {
13715     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13716     // Op0 u<= Op1:
13717     //   t = psubus Op0, Op1
13718     //   pcmpeq t, <0..0>
13719     switch (SetCCOpcode) {
13720     default: break;
13721     case ISD::SETULT: {
13722       // If the comparison is against a constant we can turn this into a
13723       // setule.  With psubus, setule does not require a swap.  This is
13724       // beneficial because the constant in the register is no longer
13725       // destructed as the destination so it can be hoisted out of a loop.
13726       // Only do this pre-AVX since vpcmp* is no longer destructive.
13727       if (Subtarget->hasAVX())
13728         break;
13729       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13730       if (ULEOp1.getNode()) {
13731         Op1 = ULEOp1;
13732         Subus = true; Invert = false; Swap = false;
13733       }
13734       break;
13735     }
13736     // Psubus is better than flip-sign because it requires no inversion.
13737     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13738     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13739     }
13740
13741     if (Subus) {
13742       Opc = X86ISD::SUBUS;
13743       FlipSigns = false;
13744     }
13745   }
13746
13747   if (Swap)
13748     std::swap(Op0, Op1);
13749
13750   // Check that the operation in question is available (most are plain SSE2,
13751   // but PCMPGTQ and PCMPEQQ have different requirements).
13752   if (VT == MVT::v2i64) {
13753     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13754       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13755
13756       // First cast everything to the right type.
13757       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13758       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13759
13760       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13761       // bits of the inputs before performing those operations. The lower
13762       // compare is always unsigned.
13763       SDValue SB;
13764       if (FlipSigns) {
13765         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13766       } else {
13767         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13768         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13769         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13770                          Sign, Zero, Sign, Zero);
13771       }
13772       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13773       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13774
13775       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13776       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13777       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13778
13779       // Create masks for only the low parts/high parts of the 64 bit integers.
13780       static const int MaskHi[] = { 1, 1, 3, 3 };
13781       static const int MaskLo[] = { 0, 0, 2, 2 };
13782       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13783       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13784       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13785
13786       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13787       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13788
13789       if (Invert)
13790         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13791
13792       return DAG.getBitcast(VT, Result);
13793     }
13794
13795     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13796       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13797       // pcmpeqd + pshufd + pand.
13798       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13799
13800       // First cast everything to the right type.
13801       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13802       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13803
13804       // Do the compare.
13805       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13806
13807       // Make sure the lower and upper halves are both all-ones.
13808       static const int Mask[] = { 1, 0, 3, 2 };
13809       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13810       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13811
13812       if (Invert)
13813         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13814
13815       return DAG.getBitcast(VT, Result);
13816     }
13817   }
13818
13819   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13820   // bits of the inputs before performing those operations.
13821   if (FlipSigns) {
13822     EVT EltVT = VT.getVectorElementType();
13823     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13824                                  VT);
13825     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13826     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13827   }
13828
13829   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13830
13831   // If the logical-not of the result is required, perform that now.
13832   if (Invert)
13833     Result = DAG.getNOT(dl, Result, VT);
13834
13835   if (MinMax)
13836     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13837
13838   if (Subus)
13839     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13840                          getZeroVector(VT, Subtarget, DAG, dl));
13841
13842   return Result;
13843 }
13844
13845 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13846
13847   MVT VT = Op.getSimpleValueType();
13848
13849   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13850
13851   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13852          && "SetCC type must be 8-bit or 1-bit integer");
13853   SDValue Op0 = Op.getOperand(0);
13854   SDValue Op1 = Op.getOperand(1);
13855   SDLoc dl(Op);
13856   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13857
13858   // Optimize to BT if possible.
13859   // Lower (X & (1 << N)) == 0 to BT(X, N).
13860   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13861   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13862   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13863       Op1.getOpcode() == ISD::Constant &&
13864       cast<ConstantSDNode>(Op1)->isNullValue() &&
13865       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13866     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13867     if (NewSetCC.getNode()) {
13868       if (VT == MVT::i1)
13869         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13870       return NewSetCC;
13871     }
13872   }
13873
13874   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13875   // these.
13876   if (Op1.getOpcode() == ISD::Constant &&
13877       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13878        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13879       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13880
13881     // If the input is a setcc, then reuse the input setcc or use a new one with
13882     // the inverted condition.
13883     if (Op0.getOpcode() == X86ISD::SETCC) {
13884       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13885       bool Invert = (CC == ISD::SETNE) ^
13886         cast<ConstantSDNode>(Op1)->isNullValue();
13887       if (!Invert)
13888         return Op0;
13889
13890       CCode = X86::GetOppositeBranchCondition(CCode);
13891       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13892                                   DAG.getConstant(CCode, dl, MVT::i8),
13893                                   Op0.getOperand(1));
13894       if (VT == MVT::i1)
13895         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13896       return SetCC;
13897     }
13898   }
13899   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13900       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13901       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13902
13903     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13904     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13905   }
13906
13907   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13908   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13909   if (X86CC == X86::COND_INVALID)
13910     return SDValue();
13911
13912   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13913   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13914   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13915                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13916   if (VT == MVT::i1)
13917     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13918   return SetCC;
13919 }
13920
13921 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13922 static bool isX86LogicalCmp(SDValue Op) {
13923   unsigned Opc = Op.getNode()->getOpcode();
13924   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13925       Opc == X86ISD::SAHF)
13926     return true;
13927   if (Op.getResNo() == 1 &&
13928       (Opc == X86ISD::ADD ||
13929        Opc == X86ISD::SUB ||
13930        Opc == X86ISD::ADC ||
13931        Opc == X86ISD::SBB ||
13932        Opc == X86ISD::SMUL ||
13933        Opc == X86ISD::UMUL ||
13934        Opc == X86ISD::INC ||
13935        Opc == X86ISD::DEC ||
13936        Opc == X86ISD::OR ||
13937        Opc == X86ISD::XOR ||
13938        Opc == X86ISD::AND))
13939     return true;
13940
13941   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13942     return true;
13943
13944   return false;
13945 }
13946
13947 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13948   if (V.getOpcode() != ISD::TRUNCATE)
13949     return false;
13950
13951   SDValue VOp0 = V.getOperand(0);
13952   unsigned InBits = VOp0.getValueSizeInBits();
13953   unsigned Bits = V.getValueSizeInBits();
13954   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13955 }
13956
13957 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13958   bool addTest = true;
13959   SDValue Cond  = Op.getOperand(0);
13960   SDValue Op1 = Op.getOperand(1);
13961   SDValue Op2 = Op.getOperand(2);
13962   SDLoc DL(Op);
13963   EVT VT = Op1.getValueType();
13964   SDValue CC;
13965
13966   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13967   // are available or VBLENDV if AVX is available.
13968   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13969   if (Cond.getOpcode() == ISD::SETCC &&
13970       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13971        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13972       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13973     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13974     int SSECC = translateX86FSETCC(
13975         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13976
13977     if (SSECC != 8) {
13978       if (Subtarget->hasAVX512()) {
13979         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13980                                   DAG.getConstant(SSECC, DL, MVT::i8));
13981         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13982       }
13983
13984       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13985                                 DAG.getConstant(SSECC, DL, MVT::i8));
13986
13987       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13988       // of 3 logic instructions for size savings and potentially speed.
13989       // Unfortunately, there is no scalar form of VBLENDV.
13990
13991       // If either operand is a constant, don't try this. We can expect to
13992       // optimize away at least one of the logic instructions later in that
13993       // case, so that sequence would be faster than a variable blend.
13994
13995       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13996       // uses XMM0 as the selection register. That may need just as many
13997       // instructions as the AND/ANDN/OR sequence due to register moves, so
13998       // don't bother.
13999
14000       if (Subtarget->hasAVX() &&
14001           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14002
14003         // Convert to vectors, do a VSELECT, and convert back to scalar.
14004         // All of the conversions should be optimized away.
14005
14006         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14007         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14008         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14009         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14010
14011         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14012         VCmp = DAG.getBitcast(VCmpVT, VCmp);
14013
14014         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14015
14016         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14017                            VSel, DAG.getIntPtrConstant(0, DL));
14018       }
14019       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14020       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14021       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14022     }
14023   }
14024
14025   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14026     SDValue Op1Scalar;
14027     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14028       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14029     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14030       Op1Scalar = Op1.getOperand(0);
14031     SDValue Op2Scalar;
14032     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14033       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14034     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14035       Op2Scalar = Op2.getOperand(0);
14036     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14037       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14038                                       Op1Scalar.getValueType(),
14039                                       Cond, Op1Scalar, Op2Scalar);
14040       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14041         return DAG.getBitcast(VT, newSelect);
14042       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14043       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14044                          DAG.getIntPtrConstant(0, DL));
14045     }
14046   }
14047
14048   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14049     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14050     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14051                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14052     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14053                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14054     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14055                                     Cond, Op1, Op2);
14056     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14057   }
14058
14059   if (Cond.getOpcode() == ISD::SETCC) {
14060     SDValue NewCond = LowerSETCC(Cond, DAG);
14061     if (NewCond.getNode())
14062       Cond = NewCond;
14063   }
14064
14065   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14066   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14067   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14068   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14069   if (Cond.getOpcode() == X86ISD::SETCC &&
14070       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14071       isZero(Cond.getOperand(1).getOperand(1))) {
14072     SDValue Cmp = Cond.getOperand(1);
14073
14074     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14075
14076     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14077         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14078       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14079
14080       SDValue CmpOp0 = Cmp.getOperand(0);
14081       // Apply further optimizations for special cases
14082       // (select (x != 0), -1, 0) -> neg & sbb
14083       // (select (x == 0), 0, -1) -> neg & sbb
14084       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14085         if (YC->isNullValue() &&
14086             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14087           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14088           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14089                                     DAG.getConstant(0, DL,
14090                                                     CmpOp0.getValueType()),
14091                                     CmpOp0);
14092           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14093                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14094                                     SDValue(Neg.getNode(), 1));
14095           return Res;
14096         }
14097
14098       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14099                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14100       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14101
14102       SDValue Res =   // Res = 0 or -1.
14103         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14104                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14105
14106       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14107         Res = DAG.getNOT(DL, Res, Res.getValueType());
14108
14109       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14110       if (!N2C || !N2C->isNullValue())
14111         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14112       return Res;
14113     }
14114   }
14115
14116   // Look past (and (setcc_carry (cmp ...)), 1).
14117   if (Cond.getOpcode() == ISD::AND &&
14118       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14119     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14120     if (C && C->getAPIntValue() == 1)
14121       Cond = Cond.getOperand(0);
14122   }
14123
14124   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14125   // setting operand in place of the X86ISD::SETCC.
14126   unsigned CondOpcode = Cond.getOpcode();
14127   if (CondOpcode == X86ISD::SETCC ||
14128       CondOpcode == X86ISD::SETCC_CARRY) {
14129     CC = Cond.getOperand(0);
14130
14131     SDValue Cmp = Cond.getOperand(1);
14132     unsigned Opc = Cmp.getOpcode();
14133     MVT VT = Op.getSimpleValueType();
14134
14135     bool IllegalFPCMov = false;
14136     if (VT.isFloatingPoint() && !VT.isVector() &&
14137         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14138       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14139
14140     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14141         Opc == X86ISD::BT) { // FIXME
14142       Cond = Cmp;
14143       addTest = false;
14144     }
14145   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14146              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14147              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14148               Cond.getOperand(0).getValueType() != MVT::i8)) {
14149     SDValue LHS = Cond.getOperand(0);
14150     SDValue RHS = Cond.getOperand(1);
14151     unsigned X86Opcode;
14152     unsigned X86Cond;
14153     SDVTList VTs;
14154     switch (CondOpcode) {
14155     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14156     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14157     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14158     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14159     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14160     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14161     default: llvm_unreachable("unexpected overflowing operator");
14162     }
14163     if (CondOpcode == ISD::UMULO)
14164       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14165                           MVT::i32);
14166     else
14167       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14168
14169     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14170
14171     if (CondOpcode == ISD::UMULO)
14172       Cond = X86Op.getValue(2);
14173     else
14174       Cond = X86Op.getValue(1);
14175
14176     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14177     addTest = false;
14178   }
14179
14180   if (addTest) {
14181     // Look past the truncate if the high bits are known zero.
14182     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14183       Cond = Cond.getOperand(0);
14184
14185     // We know the result of AND is compared against zero. Try to match
14186     // it to BT.
14187     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14188       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14189       if (NewSetCC.getNode()) {
14190         CC = NewSetCC.getOperand(0);
14191         Cond = NewSetCC.getOperand(1);
14192         addTest = false;
14193       }
14194     }
14195   }
14196
14197   if (addTest) {
14198     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14199     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14200   }
14201
14202   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14203   // a <  b ?  0 : -1 -> RES = setcc_carry
14204   // a >= b ? -1 :  0 -> RES = setcc_carry
14205   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14206   if (Cond.getOpcode() == X86ISD::SUB) {
14207     Cond = ConvertCmpIfNecessary(Cond, DAG);
14208     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14209
14210     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14211         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14212       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14213                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14214                                 Cond);
14215       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14216         return DAG.getNOT(DL, Res, Res.getValueType());
14217       return Res;
14218     }
14219   }
14220
14221   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14222   // widen the cmov and push the truncate through. This avoids introducing a new
14223   // branch during isel and doesn't add any extensions.
14224   if (Op.getValueType() == MVT::i8 &&
14225       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14226     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14227     if (T1.getValueType() == T2.getValueType() &&
14228         // Blacklist CopyFromReg to avoid partial register stalls.
14229         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14230       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14231       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14232       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14233     }
14234   }
14235
14236   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14237   // condition is true.
14238   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14239   SDValue Ops[] = { Op2, Op1, CC, Cond };
14240   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14241 }
14242
14243 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14244                                        const X86Subtarget *Subtarget,
14245                                        SelectionDAG &DAG) {
14246   MVT VT = Op->getSimpleValueType(0);
14247   SDValue In = Op->getOperand(0);
14248   MVT InVT = In.getSimpleValueType();
14249   MVT VTElt = VT.getVectorElementType();
14250   MVT InVTElt = InVT.getVectorElementType();
14251   SDLoc dl(Op);
14252
14253   // SKX processor
14254   if ((InVTElt == MVT::i1) &&
14255       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14256         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14257
14258        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14259         VTElt.getSizeInBits() <= 16)) ||
14260
14261        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14262         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14263
14264        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14265         VTElt.getSizeInBits() >= 32))))
14266     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14267
14268   unsigned int NumElts = VT.getVectorNumElements();
14269
14270   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14271     return SDValue();
14272
14273   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14274     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14275       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14276     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14277   }
14278
14279   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14280   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14281   SDValue NegOne =
14282    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14283                    ExtVT);
14284   SDValue Zero =
14285    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14286
14287   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14288   if (VT.is512BitVector())
14289     return V;
14290   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14291 }
14292
14293 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14294                                              const X86Subtarget *Subtarget,
14295                                              SelectionDAG &DAG) {
14296   SDValue In = Op->getOperand(0);
14297   MVT VT = Op->getSimpleValueType(0);
14298   MVT InVT = In.getSimpleValueType();
14299   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14300
14301   MVT InSVT = InVT.getScalarType();
14302   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14303
14304   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14305     return SDValue();
14306   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14307     return SDValue();
14308
14309   SDLoc dl(Op);
14310
14311   // SSE41 targets can use the pmovsx* instructions directly.
14312   if (Subtarget->hasSSE41())
14313     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14314
14315   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14316   SDValue Curr = In;
14317   MVT CurrVT = InVT;
14318
14319   // As SRAI is only available on i16/i32 types, we expand only up to i32
14320   // and handle i64 separately.
14321   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14322     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14323     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14324     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14325     Curr = DAG.getBitcast(CurrVT, Curr);
14326   }
14327
14328   SDValue SignExt = Curr;
14329   if (CurrVT != InVT) {
14330     unsigned SignExtShift =
14331         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14332     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14333                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14334   }
14335
14336   if (CurrVT == VT)
14337     return SignExt;
14338
14339   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14340     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14341                                DAG.getConstant(31, dl, MVT::i8));
14342     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14343     return DAG.getBitcast(VT, Ext);
14344   }
14345
14346   return SDValue();
14347 }
14348
14349 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14350                                 SelectionDAG &DAG) {
14351   MVT VT = Op->getSimpleValueType(0);
14352   SDValue In = Op->getOperand(0);
14353   MVT InVT = In.getSimpleValueType();
14354   SDLoc dl(Op);
14355
14356   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14357     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14358
14359   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14360       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14361       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14362     return SDValue();
14363
14364   if (Subtarget->hasInt256())
14365     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14366
14367   // Optimize vectors in AVX mode
14368   // Sign extend  v8i16 to v8i32 and
14369   //              v4i32 to v4i64
14370   //
14371   // Divide input vector into two parts
14372   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14373   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14374   // concat the vectors to original VT
14375
14376   unsigned NumElems = InVT.getVectorNumElements();
14377   SDValue Undef = DAG.getUNDEF(InVT);
14378
14379   SmallVector<int,8> ShufMask1(NumElems, -1);
14380   for (unsigned i = 0; i != NumElems/2; ++i)
14381     ShufMask1[i] = i;
14382
14383   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14384
14385   SmallVector<int,8> ShufMask2(NumElems, -1);
14386   for (unsigned i = 0; i != NumElems/2; ++i)
14387     ShufMask2[i] = i + NumElems/2;
14388
14389   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14390
14391   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14392                                 VT.getVectorNumElements()/2);
14393
14394   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14395   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14396
14397   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14398 }
14399
14400 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14401 // may emit an illegal shuffle but the expansion is still better than scalar
14402 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14403 // we'll emit a shuffle and a arithmetic shift.
14404 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14405 // TODO: It is possible to support ZExt by zeroing the undef values during
14406 // the shuffle phase or after the shuffle.
14407 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14408                                  SelectionDAG &DAG) {
14409   MVT RegVT = Op.getSimpleValueType();
14410   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14411   assert(RegVT.isInteger() &&
14412          "We only custom lower integer vector sext loads.");
14413
14414   // Nothing useful we can do without SSE2 shuffles.
14415   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14416
14417   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14418   SDLoc dl(Ld);
14419   EVT MemVT = Ld->getMemoryVT();
14420   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14421   unsigned RegSz = RegVT.getSizeInBits();
14422
14423   ISD::LoadExtType Ext = Ld->getExtensionType();
14424
14425   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14426          && "Only anyext and sext are currently implemented.");
14427   assert(MemVT != RegVT && "Cannot extend to the same type");
14428   assert(MemVT.isVector() && "Must load a vector from memory");
14429
14430   unsigned NumElems = RegVT.getVectorNumElements();
14431   unsigned MemSz = MemVT.getSizeInBits();
14432   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14433
14434   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14435     // The only way in which we have a legal 256-bit vector result but not the
14436     // integer 256-bit operations needed to directly lower a sextload is if we
14437     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14438     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14439     // correctly legalized. We do this late to allow the canonical form of
14440     // sextload to persist throughout the rest of the DAG combiner -- it wants
14441     // to fold together any extensions it can, and so will fuse a sign_extend
14442     // of an sextload into a sextload targeting a wider value.
14443     SDValue Load;
14444     if (MemSz == 128) {
14445       // Just switch this to a normal load.
14446       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14447                                        "it must be a legal 128-bit vector "
14448                                        "type!");
14449       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14450                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14451                   Ld->isInvariant(), Ld->getAlignment());
14452     } else {
14453       assert(MemSz < 128 &&
14454              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14455       // Do an sext load to a 128-bit vector type. We want to use the same
14456       // number of elements, but elements half as wide. This will end up being
14457       // recursively lowered by this routine, but will succeed as we definitely
14458       // have all the necessary features if we're using AVX1.
14459       EVT HalfEltVT =
14460           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14461       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14462       Load =
14463           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14464                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14465                          Ld->isNonTemporal(), Ld->isInvariant(),
14466                          Ld->getAlignment());
14467     }
14468
14469     // Replace chain users with the new chain.
14470     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14471     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14472
14473     // Finally, do a normal sign-extend to the desired register.
14474     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14475   }
14476
14477   // All sizes must be a power of two.
14478   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14479          "Non-power-of-two elements are not custom lowered!");
14480
14481   // Attempt to load the original value using scalar loads.
14482   // Find the largest scalar type that divides the total loaded size.
14483   MVT SclrLoadTy = MVT::i8;
14484   for (MVT Tp : MVT::integer_valuetypes()) {
14485     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14486       SclrLoadTy = Tp;
14487     }
14488   }
14489
14490   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14491   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14492       (64 <= MemSz))
14493     SclrLoadTy = MVT::f64;
14494
14495   // Calculate the number of scalar loads that we need to perform
14496   // in order to load our vector from memory.
14497   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14498
14499   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14500          "Can only lower sext loads with a single scalar load!");
14501
14502   unsigned loadRegZize = RegSz;
14503   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14504     loadRegZize = 128;
14505
14506   // Represent our vector as a sequence of elements which are the
14507   // largest scalar that we can load.
14508   EVT LoadUnitVecVT = EVT::getVectorVT(
14509       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14510
14511   // Represent the data using the same element type that is stored in
14512   // memory. In practice, we ''widen'' MemVT.
14513   EVT WideVecVT =
14514       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14515                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14516
14517   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14518          "Invalid vector type");
14519
14520   // We can't shuffle using an illegal type.
14521   assert(TLI.isTypeLegal(WideVecVT) &&
14522          "We only lower types that form legal widened vector types");
14523
14524   SmallVector<SDValue, 8> Chains;
14525   SDValue Ptr = Ld->getBasePtr();
14526   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14527                                       TLI.getPointerTy(DAG.getDataLayout()));
14528   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14529
14530   for (unsigned i = 0; i < NumLoads; ++i) {
14531     // Perform a single load.
14532     SDValue ScalarLoad =
14533         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14534                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14535                     Ld->getAlignment());
14536     Chains.push_back(ScalarLoad.getValue(1));
14537     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14538     // another round of DAGCombining.
14539     if (i == 0)
14540       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14541     else
14542       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14543                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14544
14545     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14546   }
14547
14548   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14549
14550   // Bitcast the loaded value to a vector of the original element type, in
14551   // the size of the target vector type.
14552   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14553   unsigned SizeRatio = RegSz / MemSz;
14554
14555   if (Ext == ISD::SEXTLOAD) {
14556     // If we have SSE4.1, we can directly emit a VSEXT node.
14557     if (Subtarget->hasSSE41()) {
14558       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14559       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14560       return Sext;
14561     }
14562
14563     // Otherwise we'll shuffle the small elements in the high bits of the
14564     // larger type and perform an arithmetic shift. If the shift is not legal
14565     // it's better to scalarize.
14566     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14567            "We can't implement a sext load without an arithmetic right shift!");
14568
14569     // Redistribute the loaded elements into the different locations.
14570     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14571     for (unsigned i = 0; i != NumElems; ++i)
14572       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14573
14574     SDValue Shuff = DAG.getVectorShuffle(
14575         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14576
14577     Shuff = DAG.getBitcast(RegVT, Shuff);
14578
14579     // Build the arithmetic shift.
14580     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14581                    MemVT.getVectorElementType().getSizeInBits();
14582     Shuff =
14583         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14584                     DAG.getConstant(Amt, dl, RegVT));
14585
14586     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14587     return Shuff;
14588   }
14589
14590   // Redistribute the loaded elements into the different locations.
14591   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14592   for (unsigned i = 0; i != NumElems; ++i)
14593     ShuffleVec[i * SizeRatio] = i;
14594
14595   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14596                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14597
14598   // Bitcast to the requested type.
14599   Shuff = DAG.getBitcast(RegVT, Shuff);
14600   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14601   return Shuff;
14602 }
14603
14604 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14605 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14606 // from the AND / OR.
14607 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14608   Opc = Op.getOpcode();
14609   if (Opc != ISD::OR && Opc != ISD::AND)
14610     return false;
14611   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14612           Op.getOperand(0).hasOneUse() &&
14613           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14614           Op.getOperand(1).hasOneUse());
14615 }
14616
14617 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14618 // 1 and that the SETCC node has a single use.
14619 static bool isXor1OfSetCC(SDValue Op) {
14620   if (Op.getOpcode() != ISD::XOR)
14621     return false;
14622   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14623   if (N1C && N1C->getAPIntValue() == 1) {
14624     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14625       Op.getOperand(0).hasOneUse();
14626   }
14627   return false;
14628 }
14629
14630 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14631   bool addTest = true;
14632   SDValue Chain = Op.getOperand(0);
14633   SDValue Cond  = Op.getOperand(1);
14634   SDValue Dest  = Op.getOperand(2);
14635   SDLoc dl(Op);
14636   SDValue CC;
14637   bool Inverted = false;
14638
14639   if (Cond.getOpcode() == ISD::SETCC) {
14640     // Check for setcc([su]{add,sub,mul}o == 0).
14641     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14642         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14643         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14644         Cond.getOperand(0).getResNo() == 1 &&
14645         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14646          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14647          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14648          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14649          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14650          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14651       Inverted = true;
14652       Cond = Cond.getOperand(0);
14653     } else {
14654       SDValue NewCond = LowerSETCC(Cond, DAG);
14655       if (NewCond.getNode())
14656         Cond = NewCond;
14657     }
14658   }
14659 #if 0
14660   // FIXME: LowerXALUO doesn't handle these!!
14661   else if (Cond.getOpcode() == X86ISD::ADD  ||
14662            Cond.getOpcode() == X86ISD::SUB  ||
14663            Cond.getOpcode() == X86ISD::SMUL ||
14664            Cond.getOpcode() == X86ISD::UMUL)
14665     Cond = LowerXALUO(Cond, DAG);
14666 #endif
14667
14668   // Look pass (and (setcc_carry (cmp ...)), 1).
14669   if (Cond.getOpcode() == ISD::AND &&
14670       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14671     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14672     if (C && C->getAPIntValue() == 1)
14673       Cond = Cond.getOperand(0);
14674   }
14675
14676   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14677   // setting operand in place of the X86ISD::SETCC.
14678   unsigned CondOpcode = Cond.getOpcode();
14679   if (CondOpcode == X86ISD::SETCC ||
14680       CondOpcode == X86ISD::SETCC_CARRY) {
14681     CC = Cond.getOperand(0);
14682
14683     SDValue Cmp = Cond.getOperand(1);
14684     unsigned Opc = Cmp.getOpcode();
14685     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14686     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14687       Cond = Cmp;
14688       addTest = false;
14689     } else {
14690       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14691       default: break;
14692       case X86::COND_O:
14693       case X86::COND_B:
14694         // These can only come from an arithmetic instruction with overflow,
14695         // e.g. SADDO, UADDO.
14696         Cond = Cond.getNode()->getOperand(1);
14697         addTest = false;
14698         break;
14699       }
14700     }
14701   }
14702   CondOpcode = Cond.getOpcode();
14703   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14704       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14705       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14706        Cond.getOperand(0).getValueType() != MVT::i8)) {
14707     SDValue LHS = Cond.getOperand(0);
14708     SDValue RHS = Cond.getOperand(1);
14709     unsigned X86Opcode;
14710     unsigned X86Cond;
14711     SDVTList VTs;
14712     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14713     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14714     // X86ISD::INC).
14715     switch (CondOpcode) {
14716     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14717     case ISD::SADDO:
14718       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14719         if (C->isOne()) {
14720           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14721           break;
14722         }
14723       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14724     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14725     case ISD::SSUBO:
14726       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14727         if (C->isOne()) {
14728           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14729           break;
14730         }
14731       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14732     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14733     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14734     default: llvm_unreachable("unexpected overflowing operator");
14735     }
14736     if (Inverted)
14737       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14738     if (CondOpcode == ISD::UMULO)
14739       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14740                           MVT::i32);
14741     else
14742       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14743
14744     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14745
14746     if (CondOpcode == ISD::UMULO)
14747       Cond = X86Op.getValue(2);
14748     else
14749       Cond = X86Op.getValue(1);
14750
14751     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14752     addTest = false;
14753   } else {
14754     unsigned CondOpc;
14755     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14756       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14757       if (CondOpc == ISD::OR) {
14758         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14759         // two branches instead of an explicit OR instruction with a
14760         // separate test.
14761         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14762             isX86LogicalCmp(Cmp)) {
14763           CC = Cond.getOperand(0).getOperand(0);
14764           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14765                               Chain, Dest, CC, Cmp);
14766           CC = Cond.getOperand(1).getOperand(0);
14767           Cond = Cmp;
14768           addTest = false;
14769         }
14770       } else { // ISD::AND
14771         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14772         // two branches instead of an explicit AND instruction with a
14773         // separate test. However, we only do this if this block doesn't
14774         // have a fall-through edge, because this requires an explicit
14775         // jmp when the condition is false.
14776         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14777             isX86LogicalCmp(Cmp) &&
14778             Op.getNode()->hasOneUse()) {
14779           X86::CondCode CCode =
14780             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14781           CCode = X86::GetOppositeBranchCondition(CCode);
14782           CC = DAG.getConstant(CCode, dl, MVT::i8);
14783           SDNode *User = *Op.getNode()->use_begin();
14784           // Look for an unconditional branch following this conditional branch.
14785           // We need this because we need to reverse the successors in order
14786           // to implement FCMP_OEQ.
14787           if (User->getOpcode() == ISD::BR) {
14788             SDValue FalseBB = User->getOperand(1);
14789             SDNode *NewBR =
14790               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14791             assert(NewBR == User);
14792             (void)NewBR;
14793             Dest = FalseBB;
14794
14795             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14796                                 Chain, Dest, CC, Cmp);
14797             X86::CondCode CCode =
14798               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14799             CCode = X86::GetOppositeBranchCondition(CCode);
14800             CC = DAG.getConstant(CCode, dl, MVT::i8);
14801             Cond = Cmp;
14802             addTest = false;
14803           }
14804         }
14805       }
14806     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14807       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14808       // It should be transformed during dag combiner except when the condition
14809       // is set by a arithmetics with overflow node.
14810       X86::CondCode CCode =
14811         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14812       CCode = X86::GetOppositeBranchCondition(CCode);
14813       CC = DAG.getConstant(CCode, dl, MVT::i8);
14814       Cond = Cond.getOperand(0).getOperand(1);
14815       addTest = false;
14816     } else if (Cond.getOpcode() == ISD::SETCC &&
14817                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14818       // For FCMP_OEQ, we can emit
14819       // two branches instead of an explicit AND instruction with a
14820       // separate test. However, we only do this if this block doesn't
14821       // have a fall-through edge, because this requires an explicit
14822       // jmp when the condition is false.
14823       if (Op.getNode()->hasOneUse()) {
14824         SDNode *User = *Op.getNode()->use_begin();
14825         // Look for an unconditional branch following this conditional branch.
14826         // We need this because we need to reverse the successors in order
14827         // to implement FCMP_OEQ.
14828         if (User->getOpcode() == ISD::BR) {
14829           SDValue FalseBB = User->getOperand(1);
14830           SDNode *NewBR =
14831             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14832           assert(NewBR == User);
14833           (void)NewBR;
14834           Dest = FalseBB;
14835
14836           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14837                                     Cond.getOperand(0), Cond.getOperand(1));
14838           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14839           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14840           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14841                               Chain, Dest, CC, Cmp);
14842           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14843           Cond = Cmp;
14844           addTest = false;
14845         }
14846       }
14847     } else if (Cond.getOpcode() == ISD::SETCC &&
14848                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14849       // For FCMP_UNE, we can emit
14850       // two branches instead of an explicit AND instruction with a
14851       // separate test. However, we only do this if this block doesn't
14852       // have a fall-through edge, because this requires an explicit
14853       // jmp when the condition is false.
14854       if (Op.getNode()->hasOneUse()) {
14855         SDNode *User = *Op.getNode()->use_begin();
14856         // Look for an unconditional branch following this conditional branch.
14857         // We need this because we need to reverse the successors in order
14858         // to implement FCMP_UNE.
14859         if (User->getOpcode() == ISD::BR) {
14860           SDValue FalseBB = User->getOperand(1);
14861           SDNode *NewBR =
14862             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14863           assert(NewBR == User);
14864           (void)NewBR;
14865
14866           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14867                                     Cond.getOperand(0), Cond.getOperand(1));
14868           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14869           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14870           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14871                               Chain, Dest, CC, Cmp);
14872           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14873           Cond = Cmp;
14874           addTest = false;
14875           Dest = FalseBB;
14876         }
14877       }
14878     }
14879   }
14880
14881   if (addTest) {
14882     // Look pass the truncate if the high bits are known zero.
14883     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14884         Cond = Cond.getOperand(0);
14885
14886     // We know the result of AND is compared against zero. Try to match
14887     // it to BT.
14888     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14889       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14890       if (NewSetCC.getNode()) {
14891         CC = NewSetCC.getOperand(0);
14892         Cond = NewSetCC.getOperand(1);
14893         addTest = false;
14894       }
14895     }
14896   }
14897
14898   if (addTest) {
14899     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14900     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14901     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14902   }
14903   Cond = ConvertCmpIfNecessary(Cond, DAG);
14904   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14905                      Chain, Dest, CC, Cond);
14906 }
14907
14908 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14909 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14910 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14911 // that the guard pages used by the OS virtual memory manager are allocated in
14912 // correct sequence.
14913 SDValue
14914 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14915                                            SelectionDAG &DAG) const {
14916   MachineFunction &MF = DAG.getMachineFunction();
14917   bool SplitStack = MF.shouldSplitStack();
14918   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14919                SplitStack;
14920   SDLoc dl(Op);
14921
14922   if (!Lower) {
14923     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14924     SDNode* Node = Op.getNode();
14925
14926     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14927     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14928         " not tell us which reg is the stack pointer!");
14929     EVT VT = Node->getValueType(0);
14930     SDValue Tmp1 = SDValue(Node, 0);
14931     SDValue Tmp2 = SDValue(Node, 1);
14932     SDValue Tmp3 = Node->getOperand(2);
14933     SDValue Chain = Tmp1.getOperand(0);
14934
14935     // Chain the dynamic stack allocation so that it doesn't modify the stack
14936     // pointer when other instructions are using the stack.
14937     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14938         SDLoc(Node));
14939
14940     SDValue Size = Tmp2.getOperand(1);
14941     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14942     Chain = SP.getValue(1);
14943     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14944     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14945     unsigned StackAlign = TFI.getStackAlignment();
14946     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14947     if (Align > StackAlign)
14948       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14949           DAG.getConstant(-(uint64_t)Align, dl, VT));
14950     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14951
14952     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14953         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14954         SDLoc(Node));
14955
14956     SDValue Ops[2] = { Tmp1, Tmp2 };
14957     return DAG.getMergeValues(Ops, dl);
14958   }
14959
14960   // Get the inputs.
14961   SDValue Chain = Op.getOperand(0);
14962   SDValue Size  = Op.getOperand(1);
14963   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14964   EVT VT = Op.getNode()->getValueType(0);
14965
14966   bool Is64Bit = Subtarget->is64Bit();
14967   MVT SPTy = getPointerTy(DAG.getDataLayout());
14968
14969   if (SplitStack) {
14970     MachineRegisterInfo &MRI = MF.getRegInfo();
14971
14972     if (Is64Bit) {
14973       // The 64 bit implementation of segmented stacks needs to clobber both r10
14974       // r11. This makes it impossible to use it along with nested parameters.
14975       const Function *F = MF.getFunction();
14976
14977       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14978            I != E; ++I)
14979         if (I->hasNestAttr())
14980           report_fatal_error("Cannot use segmented stacks with functions that "
14981                              "have nested arguments.");
14982     }
14983
14984     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14985     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14986     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14987     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14988                                 DAG.getRegister(Vreg, SPTy));
14989     SDValue Ops1[2] = { Value, Chain };
14990     return DAG.getMergeValues(Ops1, dl);
14991   } else {
14992     SDValue Flag;
14993     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14994
14995     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14996     Flag = Chain.getValue(1);
14997     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14998
14999     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15000
15001     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15002     unsigned SPReg = RegInfo->getStackRegister();
15003     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15004     Chain = SP.getValue(1);
15005
15006     if (Align) {
15007       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15008                        DAG.getConstant(-(uint64_t)Align, dl, VT));
15009       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15010     }
15011
15012     SDValue Ops1[2] = { SP, Chain };
15013     return DAG.getMergeValues(Ops1, dl);
15014   }
15015 }
15016
15017 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15018   MachineFunction &MF = DAG.getMachineFunction();
15019   auto PtrVT = getPointerTy(MF.getDataLayout());
15020   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15021
15022   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15023   SDLoc DL(Op);
15024
15025   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
15026     // vastart just stores the address of the VarArgsFrameIndex slot into the
15027     // memory location argument.
15028     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15029     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15030                         MachinePointerInfo(SV), false, false, 0);
15031   }
15032
15033   // __va_list_tag:
15034   //   gp_offset         (0 - 6 * 8)
15035   //   fp_offset         (48 - 48 + 8 * 16)
15036   //   overflow_arg_area (point to parameters coming in memory).
15037   //   reg_save_area
15038   SmallVector<SDValue, 8> MemOps;
15039   SDValue FIN = Op.getOperand(1);
15040   // Store gp_offset
15041   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15042                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15043                                                DL, MVT::i32),
15044                                FIN, MachinePointerInfo(SV), false, false, 0);
15045   MemOps.push_back(Store);
15046
15047   // Store fp_offset
15048   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15049   Store = DAG.getStore(Op.getOperand(0), DL,
15050                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15051                                        MVT::i32),
15052                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15053   MemOps.push_back(Store);
15054
15055   // Store ptr to overflow_arg_area
15056   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15057   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15058   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15059                        MachinePointerInfo(SV, 8),
15060                        false, false, 0);
15061   MemOps.push_back(Store);
15062
15063   // Store ptr to reg_save_area.
15064   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15065   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15066   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15067                        MachinePointerInfo(SV, 16), false, false, 0);
15068   MemOps.push_back(Store);
15069   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15070 }
15071
15072 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15073   assert(Subtarget->is64Bit() &&
15074          "LowerVAARG only handles 64-bit va_arg!");
15075   assert((Subtarget->isTargetLinux() ||
15076           Subtarget->isTargetDarwin()) &&
15077           "Unhandled target in LowerVAARG");
15078   assert(Op.getNode()->getNumOperands() == 4);
15079   SDValue Chain = Op.getOperand(0);
15080   SDValue SrcPtr = Op.getOperand(1);
15081   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15082   unsigned Align = Op.getConstantOperandVal(3);
15083   SDLoc dl(Op);
15084
15085   EVT ArgVT = Op.getNode()->getValueType(0);
15086   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15087   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15088   uint8_t ArgMode;
15089
15090   // Decide which area this value should be read from.
15091   // TODO: Implement the AMD64 ABI in its entirety. This simple
15092   // selection mechanism works only for the basic types.
15093   if (ArgVT == MVT::f80) {
15094     llvm_unreachable("va_arg for f80 not yet implemented");
15095   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15096     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15097   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15098     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15099   } else {
15100     llvm_unreachable("Unhandled argument type in LowerVAARG");
15101   }
15102
15103   if (ArgMode == 2) {
15104     // Sanity Check: Make sure using fp_offset makes sense.
15105     assert(!Subtarget->useSoftFloat() &&
15106            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15107                Attribute::NoImplicitFloat)) &&
15108            Subtarget->hasSSE1());
15109   }
15110
15111   // Insert VAARG_64 node into the DAG
15112   // VAARG_64 returns two values: Variable Argument Address, Chain
15113   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15114                        DAG.getConstant(ArgMode, dl, MVT::i8),
15115                        DAG.getConstant(Align, dl, MVT::i32)};
15116   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15117   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15118                                           VTs, InstOps, MVT::i64,
15119                                           MachinePointerInfo(SV),
15120                                           /*Align=*/0,
15121                                           /*Volatile=*/false,
15122                                           /*ReadMem=*/true,
15123                                           /*WriteMem=*/true);
15124   Chain = VAARG.getValue(1);
15125
15126   // Load the next argument and return it
15127   return DAG.getLoad(ArgVT, dl,
15128                      Chain,
15129                      VAARG,
15130                      MachinePointerInfo(),
15131                      false, false, false, 0);
15132 }
15133
15134 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15135                            SelectionDAG &DAG) {
15136   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15137   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15138   SDValue Chain = Op.getOperand(0);
15139   SDValue DstPtr = Op.getOperand(1);
15140   SDValue SrcPtr = Op.getOperand(2);
15141   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15142   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15143   SDLoc DL(Op);
15144
15145   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15146                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15147                        false, false,
15148                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15149 }
15150
15151 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15152 // amount is a constant. Takes immediate version of shift as input.
15153 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15154                                           SDValue SrcOp, uint64_t ShiftAmt,
15155                                           SelectionDAG &DAG) {
15156   MVT ElementType = VT.getVectorElementType();
15157
15158   // Fold this packed shift into its first operand if ShiftAmt is 0.
15159   if (ShiftAmt == 0)
15160     return SrcOp;
15161
15162   // Check for ShiftAmt >= element width
15163   if (ShiftAmt >= ElementType.getSizeInBits()) {
15164     if (Opc == X86ISD::VSRAI)
15165       ShiftAmt = ElementType.getSizeInBits() - 1;
15166     else
15167       return DAG.getConstant(0, dl, VT);
15168   }
15169
15170   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15171          && "Unknown target vector shift-by-constant node");
15172
15173   // Fold this packed vector shift into a build vector if SrcOp is a
15174   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15175   if (VT == SrcOp.getSimpleValueType() &&
15176       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15177     SmallVector<SDValue, 8> Elts;
15178     unsigned NumElts = SrcOp->getNumOperands();
15179     ConstantSDNode *ND;
15180
15181     switch(Opc) {
15182     default: llvm_unreachable(nullptr);
15183     case X86ISD::VSHLI:
15184       for (unsigned i=0; i!=NumElts; ++i) {
15185         SDValue CurrentOp = SrcOp->getOperand(i);
15186         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15187           Elts.push_back(CurrentOp);
15188           continue;
15189         }
15190         ND = cast<ConstantSDNode>(CurrentOp);
15191         const APInt &C = ND->getAPIntValue();
15192         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15193       }
15194       break;
15195     case X86ISD::VSRLI:
15196       for (unsigned i=0; i!=NumElts; ++i) {
15197         SDValue CurrentOp = SrcOp->getOperand(i);
15198         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15199           Elts.push_back(CurrentOp);
15200           continue;
15201         }
15202         ND = cast<ConstantSDNode>(CurrentOp);
15203         const APInt &C = ND->getAPIntValue();
15204         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15205       }
15206       break;
15207     case X86ISD::VSRAI:
15208       for (unsigned i=0; i!=NumElts; ++i) {
15209         SDValue CurrentOp = SrcOp->getOperand(i);
15210         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15211           Elts.push_back(CurrentOp);
15212           continue;
15213         }
15214         ND = cast<ConstantSDNode>(CurrentOp);
15215         const APInt &C = ND->getAPIntValue();
15216         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15217       }
15218       break;
15219     }
15220
15221     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15222   }
15223
15224   return DAG.getNode(Opc, dl, VT, SrcOp,
15225                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15226 }
15227
15228 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15229 // may or may not be a constant. Takes immediate version of shift as input.
15230 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15231                                    SDValue SrcOp, SDValue ShAmt,
15232                                    SelectionDAG &DAG) {
15233   MVT SVT = ShAmt.getSimpleValueType();
15234   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15235
15236   // Catch shift-by-constant.
15237   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15238     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15239                                       CShAmt->getZExtValue(), DAG);
15240
15241   // Change opcode to non-immediate version
15242   switch (Opc) {
15243     default: llvm_unreachable("Unknown target vector shift node");
15244     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15245     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15246     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15247   }
15248
15249   const X86Subtarget &Subtarget =
15250       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15251   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15252       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15253     // Let the shuffle legalizer expand this shift amount node.
15254     SDValue Op0 = ShAmt.getOperand(0);
15255     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15256     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15257   } else {
15258     // Need to build a vector containing shift amount.
15259     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15260     SmallVector<SDValue, 4> ShOps;
15261     ShOps.push_back(ShAmt);
15262     if (SVT == MVT::i32) {
15263       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15264       ShOps.push_back(DAG.getUNDEF(SVT));
15265     }
15266     ShOps.push_back(DAG.getUNDEF(SVT));
15267
15268     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15269     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15270   }
15271
15272   // The return type has to be a 128-bit type with the same element
15273   // type as the input type.
15274   MVT EltVT = VT.getVectorElementType();
15275   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15276
15277   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15278   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15279 }
15280
15281 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15282 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15283 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15284 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15285                                     SDValue PreservedSrc,
15286                                     const X86Subtarget *Subtarget,
15287                                     SelectionDAG &DAG) {
15288     EVT VT = Op.getValueType();
15289     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15290                                   MVT::i1, VT.getVectorNumElements());
15291     SDValue VMask = SDValue();
15292     unsigned OpcodeSelect = ISD::VSELECT;
15293     SDLoc dl(Op);
15294
15295     assert(MaskVT.isSimple() && "invalid mask type");
15296
15297     if (isAllOnes(Mask))
15298       return Op;
15299
15300     if (MaskVT.bitsGT(Mask.getValueType())) {
15301       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15302                                          MaskVT.getSizeInBits());
15303       VMask = DAG.getBitcast(MaskVT,
15304                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15305     } else {
15306       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15307                                        Mask.getValueType().getSizeInBits());
15308       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15309       // are extracted by EXTRACT_SUBVECTOR.
15310       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15311                           DAG.getBitcast(BitcastVT, Mask),
15312                           DAG.getIntPtrConstant(0, dl));
15313     }
15314
15315     switch (Op.getOpcode()) {
15316       default: break;
15317       case X86ISD::PCMPEQM:
15318       case X86ISD::PCMPGTM:
15319       case X86ISD::CMPM:
15320       case X86ISD::CMPMU:
15321         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15322       case X86ISD::VTRUNC:
15323       case X86ISD::VTRUNCS:
15324       case X86ISD::VTRUNCUS:
15325         // We can't use ISD::VSELECT here because it is not always "Legal"
15326         // for the destination type. For example vpmovqb require only AVX512
15327         // and vselect that can operate on byte element type require BWI
15328         OpcodeSelect = X86ISD::SELECT;
15329         break;
15330     }
15331     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15332       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15333     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15334 }
15335
15336 /// \brief Creates an SDNode for a predicated scalar operation.
15337 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15338 /// The mask is coming as MVT::i8 and it should be truncated
15339 /// to MVT::i1 while lowering masking intrinsics.
15340 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15341 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15342 /// for a scalar instruction.
15343 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15344                                     SDValue PreservedSrc,
15345                                     const X86Subtarget *Subtarget,
15346                                     SelectionDAG &DAG) {
15347     if (isAllOnes(Mask))
15348       return Op;
15349
15350     EVT VT = Op.getValueType();
15351     SDLoc dl(Op);
15352     // The mask should be of type MVT::i1
15353     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15354
15355     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15356       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15357     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15358 }
15359
15360 static int getSEHRegistrationNodeSize(const Function *Fn) {
15361   if (!Fn->hasPersonalityFn())
15362     report_fatal_error(
15363         "querying registration node size for function without personality");
15364   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15365   // WinEHStatePass for the full struct definition.
15366   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15367   case EHPersonality::MSVC_X86SEH: return 24;
15368   case EHPersonality::MSVC_CXX: return 16;
15369   default: break;
15370   }
15371   report_fatal_error("can only recover FP for MSVC EH personality functions");
15372 }
15373
15374 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15375 /// function or when returning to a parent frame after catching an exception, we
15376 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15377 /// Here's the math:
15378 ///   RegNodeBase = EntryEBP - RegNodeSize
15379 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15380 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15381 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15382 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15383                                    SDValue EntryEBP) {
15384   MachineFunction &MF = DAG.getMachineFunction();
15385   SDLoc dl;
15386
15387   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15388   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15389
15390   // It's possible that the parent function no longer has a personality function
15391   // if the exceptional code was optimized away, in which case we just return
15392   // the incoming EBP.
15393   if (!Fn->hasPersonalityFn())
15394     return EntryEBP;
15395
15396   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15397
15398   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15399   // registration.
15400   MCSymbol *OffsetSym =
15401       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15402           GlobalValue::getRealLinkageName(Fn->getName()));
15403   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15404   SDValue RegNodeFrameOffset =
15405       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15406
15407   // RegNodeBase = EntryEBP - RegNodeSize
15408   // ParentFP = RegNodeBase - RegNodeFrameOffset
15409   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15410                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15411   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15412 }
15413
15414 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15415                                        SelectionDAG &DAG) {
15416   SDLoc dl(Op);
15417   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15418   EVT VT = Op.getValueType();
15419   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15420   if (IntrData) {
15421     switch(IntrData->Type) {
15422     case INTR_TYPE_1OP:
15423       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15424     case INTR_TYPE_2OP:
15425       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15426         Op.getOperand(2));
15427     case INTR_TYPE_3OP:
15428       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15429         Op.getOperand(2), Op.getOperand(3));
15430     case INTR_TYPE_4OP:
15431       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15432         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15433     case INTR_TYPE_1OP_MASK_RM: {
15434       SDValue Src = Op.getOperand(1);
15435       SDValue PassThru = Op.getOperand(2);
15436       SDValue Mask = Op.getOperand(3);
15437       SDValue RoundingMode;
15438       // We allways add rounding mode to the Node.
15439       // If the rounding mode is not specified, we add the
15440       // "current direction" mode.
15441       if (Op.getNumOperands() == 4)
15442         RoundingMode =
15443           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15444       else
15445         RoundingMode = Op.getOperand(4);
15446       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15447       if (IntrWithRoundingModeOpcode != 0)
15448         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15449             X86::STATIC_ROUNDING::CUR_DIRECTION)
15450           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15451                                       dl, Op.getValueType(), Src, RoundingMode),
15452                                       Mask, PassThru, Subtarget, DAG);
15453       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15454                                               RoundingMode),
15455                                   Mask, PassThru, Subtarget, DAG);
15456     }
15457     case INTR_TYPE_1OP_MASK: {
15458       SDValue Src = Op.getOperand(1);
15459       SDValue PassThru = Op.getOperand(2);
15460       SDValue Mask = Op.getOperand(3);
15461       // We add rounding mode to the Node when
15462       //   - RM Opcode is specified and
15463       //   - RM is not "current direction".
15464       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15465       if (IntrWithRoundingModeOpcode != 0) {
15466         SDValue Rnd = Op.getOperand(4);
15467         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15468         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15469           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15470                                       dl, Op.getValueType(),
15471                                       Src, Rnd),
15472                                       Mask, PassThru, Subtarget, DAG);
15473         }
15474       }
15475       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15476                                   Mask, PassThru, Subtarget, DAG);
15477     }
15478     case INTR_TYPE_SCALAR_MASK_RM: {
15479       SDValue Src1 = Op.getOperand(1);
15480       SDValue Src2 = Op.getOperand(2);
15481       SDValue Src0 = Op.getOperand(3);
15482       SDValue Mask = Op.getOperand(4);
15483       // There are 2 kinds of intrinsics in this group:
15484       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15485       // (2) With rounding mode and sae - 7 operands.
15486       if (Op.getNumOperands() == 6) {
15487         SDValue Sae  = Op.getOperand(5);
15488         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15489         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15490                                                 Sae),
15491                                     Mask, Src0, Subtarget, DAG);
15492       }
15493       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15494       SDValue RoundingMode  = Op.getOperand(5);
15495       SDValue Sae  = Op.getOperand(6);
15496       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15497                                               RoundingMode, Sae),
15498                                   Mask, Src0, Subtarget, DAG);
15499     }
15500     case INTR_TYPE_2OP_MASK: {
15501       SDValue Src1 = Op.getOperand(1);
15502       SDValue Src2 = Op.getOperand(2);
15503       SDValue PassThru = Op.getOperand(3);
15504       SDValue Mask = Op.getOperand(4);
15505       // We specify 2 possible opcodes for intrinsics with rounding modes.
15506       // First, we check if the intrinsic may have non-default rounding mode,
15507       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15508       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15509       if (IntrWithRoundingModeOpcode != 0) {
15510         SDValue Rnd = Op.getOperand(5);
15511         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15512         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15513           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15514                                       dl, Op.getValueType(),
15515                                       Src1, Src2, Rnd),
15516                                       Mask, PassThru, Subtarget, DAG);
15517         }
15518       }
15519       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15520                                               Src1,Src2),
15521                                   Mask, PassThru, Subtarget, DAG);
15522     }
15523     case INTR_TYPE_2OP_MASK_RM: {
15524       SDValue Src1 = Op.getOperand(1);
15525       SDValue Src2 = Op.getOperand(2);
15526       SDValue PassThru = Op.getOperand(3);
15527       SDValue Mask = Op.getOperand(4);
15528       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15529       // First, we check if the intrinsic have rounding mode (6 operands),
15530       // if not, we set rounding mode to "current".
15531       SDValue Rnd;
15532       if (Op.getNumOperands() == 6)
15533         Rnd = Op.getOperand(5);
15534       else
15535         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15536       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15537                                               Src1, Src2, Rnd),
15538                                   Mask, PassThru, Subtarget, DAG);
15539     }
15540     case INTR_TYPE_3OP_MASK_RM: {
15541       SDValue Src1 = Op.getOperand(1);
15542       SDValue Src2 = Op.getOperand(2);
15543       SDValue Imm = Op.getOperand(3);
15544       SDValue PassThru = Op.getOperand(4);
15545       SDValue Mask = Op.getOperand(5);
15546       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15547       // First, we check if the intrinsic have rounding mode (7 operands),
15548       // if not, we set rounding mode to "current".
15549       SDValue Rnd;
15550       if (Op.getNumOperands() == 7)
15551         Rnd = Op.getOperand(6);
15552       else
15553         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15554       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15555         Src1, Src2, Imm, Rnd),
15556         Mask, PassThru, Subtarget, DAG);
15557     }
15558     case INTR_TYPE_3OP_MASK: {
15559       SDValue Src1 = Op.getOperand(1);
15560       SDValue Src2 = Op.getOperand(2);
15561       SDValue Src3 = Op.getOperand(3);
15562       SDValue PassThru = Op.getOperand(4);
15563       SDValue Mask = Op.getOperand(5);
15564       // We specify 2 possible opcodes for intrinsics with rounding modes.
15565       // First, we check if the intrinsic may have non-default rounding mode,
15566       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15567       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15568       if (IntrWithRoundingModeOpcode != 0) {
15569         SDValue Rnd = Op.getOperand(6);
15570         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15571         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15572           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15573                                       dl, Op.getValueType(),
15574                                       Src1, Src2, Src3, Rnd),
15575                                       Mask, PassThru, Subtarget, DAG);
15576         }
15577       }
15578       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15579                                               Src1, Src2, Src3),
15580                                   Mask, PassThru, Subtarget, DAG);
15581     }
15582     case VPERM_3OP_MASKZ:
15583     case VPERM_3OP_MASK:
15584     case FMA_OP_MASK3:
15585     case FMA_OP_MASKZ:
15586     case FMA_OP_MASK: {
15587       SDValue Src1 = Op.getOperand(1);
15588       SDValue Src2 = Op.getOperand(2);
15589       SDValue Src3 = Op.getOperand(3);
15590       SDValue Mask = Op.getOperand(4);
15591       EVT VT = Op.getValueType();
15592       SDValue PassThru = SDValue();
15593
15594       // set PassThru element
15595       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15596         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15597       else if (IntrData->Type == FMA_OP_MASK3)
15598         PassThru = Src3;
15599       else
15600         PassThru = Src1;
15601
15602       // We specify 2 possible opcodes for intrinsics with rounding modes.
15603       // First, we check if the intrinsic may have non-default rounding mode,
15604       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15605       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15606       if (IntrWithRoundingModeOpcode != 0) {
15607         SDValue Rnd = Op.getOperand(5);
15608         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15609             X86::STATIC_ROUNDING::CUR_DIRECTION)
15610           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15611                                                   dl, Op.getValueType(),
15612                                                   Src1, Src2, Src3, Rnd),
15613                                       Mask, PassThru, Subtarget, DAG);
15614       }
15615       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15616                                               dl, Op.getValueType(),
15617                                               Src1, Src2, Src3),
15618                                   Mask, PassThru, Subtarget, DAG);
15619     }
15620     case CMP_MASK:
15621     case CMP_MASK_CC: {
15622       // Comparison intrinsics with masks.
15623       // Example of transformation:
15624       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15625       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15626       // (i8 (bitcast
15627       //   (v8i1 (insert_subvector undef,
15628       //           (v2i1 (and (PCMPEQM %a, %b),
15629       //                      (extract_subvector
15630       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15631       EVT VT = Op.getOperand(1).getValueType();
15632       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15633                                     VT.getVectorNumElements());
15634       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15635       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15636                                        Mask.getValueType().getSizeInBits());
15637       SDValue Cmp;
15638       if (IntrData->Type == CMP_MASK_CC) {
15639         SDValue CC = Op.getOperand(3);
15640         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15641         // We specify 2 possible opcodes for intrinsics with rounding modes.
15642         // First, we check if the intrinsic may have non-default rounding mode,
15643         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15644         if (IntrData->Opc1 != 0) {
15645           SDValue Rnd = Op.getOperand(5);
15646           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15647               X86::STATIC_ROUNDING::CUR_DIRECTION)
15648             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15649                               Op.getOperand(2), CC, Rnd);
15650         }
15651         //default rounding mode
15652         if(!Cmp.getNode())
15653             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15654                               Op.getOperand(2), CC);
15655
15656       } else {
15657         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15658         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15659                           Op.getOperand(2));
15660       }
15661       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15662                                              DAG.getTargetConstant(0, dl,
15663                                                                    MaskVT),
15664                                              Subtarget, DAG);
15665       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15666                                 DAG.getUNDEF(BitcastVT), CmpMask,
15667                                 DAG.getIntPtrConstant(0, dl));
15668       return DAG.getBitcast(Op.getValueType(), Res);
15669     }
15670     case COMI: { // Comparison intrinsics
15671       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15672       SDValue LHS = Op.getOperand(1);
15673       SDValue RHS = Op.getOperand(2);
15674       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15675       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15676       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15677       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15678                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15679       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15680     }
15681     case VSHIFT:
15682       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15683                                  Op.getOperand(1), Op.getOperand(2), DAG);
15684     case VSHIFT_MASK:
15685       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15686                                                       Op.getSimpleValueType(),
15687                                                       Op.getOperand(1),
15688                                                       Op.getOperand(2), DAG),
15689                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15690                                   DAG);
15691     case COMPRESS_EXPAND_IN_REG: {
15692       SDValue Mask = Op.getOperand(3);
15693       SDValue DataToCompress = Op.getOperand(1);
15694       SDValue PassThru = Op.getOperand(2);
15695       if (isAllOnes(Mask)) // return data as is
15696         return Op.getOperand(1);
15697
15698       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15699                                               DataToCompress),
15700                                   Mask, PassThru, Subtarget, DAG);
15701     }
15702     case BLEND: {
15703       SDValue Mask = Op.getOperand(3);
15704       EVT VT = Op.getValueType();
15705       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15706                                     VT.getVectorNumElements());
15707       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15708                                        Mask.getValueType().getSizeInBits());
15709       SDLoc dl(Op);
15710       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15711                                   DAG.getBitcast(BitcastVT, Mask),
15712                                   DAG.getIntPtrConstant(0, dl));
15713       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15714                          Op.getOperand(2));
15715     }
15716     default:
15717       break;
15718     }
15719   }
15720
15721   switch (IntNo) {
15722   default: return SDValue();    // Don't custom lower most intrinsics.
15723
15724   case Intrinsic::x86_avx2_permd:
15725   case Intrinsic::x86_avx2_permps:
15726     // Operands intentionally swapped. Mask is last operand to intrinsic,
15727     // but second operand for node/instruction.
15728     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15729                        Op.getOperand(2), Op.getOperand(1));
15730
15731   // ptest and testp intrinsics. The intrinsic these come from are designed to
15732   // return an integer value, not just an instruction so lower it to the ptest
15733   // or testp pattern and a setcc for the result.
15734   case Intrinsic::x86_sse41_ptestz:
15735   case Intrinsic::x86_sse41_ptestc:
15736   case Intrinsic::x86_sse41_ptestnzc:
15737   case Intrinsic::x86_avx_ptestz_256:
15738   case Intrinsic::x86_avx_ptestc_256:
15739   case Intrinsic::x86_avx_ptestnzc_256:
15740   case Intrinsic::x86_avx_vtestz_ps:
15741   case Intrinsic::x86_avx_vtestc_ps:
15742   case Intrinsic::x86_avx_vtestnzc_ps:
15743   case Intrinsic::x86_avx_vtestz_pd:
15744   case Intrinsic::x86_avx_vtestc_pd:
15745   case Intrinsic::x86_avx_vtestnzc_pd:
15746   case Intrinsic::x86_avx_vtestz_ps_256:
15747   case Intrinsic::x86_avx_vtestc_ps_256:
15748   case Intrinsic::x86_avx_vtestnzc_ps_256:
15749   case Intrinsic::x86_avx_vtestz_pd_256:
15750   case Intrinsic::x86_avx_vtestc_pd_256:
15751   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15752     bool IsTestPacked = false;
15753     unsigned X86CC;
15754     switch (IntNo) {
15755     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15756     case Intrinsic::x86_avx_vtestz_ps:
15757     case Intrinsic::x86_avx_vtestz_pd:
15758     case Intrinsic::x86_avx_vtestz_ps_256:
15759     case Intrinsic::x86_avx_vtestz_pd_256:
15760       IsTestPacked = true; // Fallthrough
15761     case Intrinsic::x86_sse41_ptestz:
15762     case Intrinsic::x86_avx_ptestz_256:
15763       // ZF = 1
15764       X86CC = X86::COND_E;
15765       break;
15766     case Intrinsic::x86_avx_vtestc_ps:
15767     case Intrinsic::x86_avx_vtestc_pd:
15768     case Intrinsic::x86_avx_vtestc_ps_256:
15769     case Intrinsic::x86_avx_vtestc_pd_256:
15770       IsTestPacked = true; // Fallthrough
15771     case Intrinsic::x86_sse41_ptestc:
15772     case Intrinsic::x86_avx_ptestc_256:
15773       // CF = 1
15774       X86CC = X86::COND_B;
15775       break;
15776     case Intrinsic::x86_avx_vtestnzc_ps:
15777     case Intrinsic::x86_avx_vtestnzc_pd:
15778     case Intrinsic::x86_avx_vtestnzc_ps_256:
15779     case Intrinsic::x86_avx_vtestnzc_pd_256:
15780       IsTestPacked = true; // Fallthrough
15781     case Intrinsic::x86_sse41_ptestnzc:
15782     case Intrinsic::x86_avx_ptestnzc_256:
15783       // ZF and CF = 0
15784       X86CC = X86::COND_A;
15785       break;
15786     }
15787
15788     SDValue LHS = Op.getOperand(1);
15789     SDValue RHS = Op.getOperand(2);
15790     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15791     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15792     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15793     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15794     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15795   }
15796   case Intrinsic::x86_avx512_kortestz_w:
15797   case Intrinsic::x86_avx512_kortestc_w: {
15798     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15799     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15800     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15801     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15802     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15803     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15804     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15805   }
15806
15807   case Intrinsic::x86_sse42_pcmpistria128:
15808   case Intrinsic::x86_sse42_pcmpestria128:
15809   case Intrinsic::x86_sse42_pcmpistric128:
15810   case Intrinsic::x86_sse42_pcmpestric128:
15811   case Intrinsic::x86_sse42_pcmpistrio128:
15812   case Intrinsic::x86_sse42_pcmpestrio128:
15813   case Intrinsic::x86_sse42_pcmpistris128:
15814   case Intrinsic::x86_sse42_pcmpestris128:
15815   case Intrinsic::x86_sse42_pcmpistriz128:
15816   case Intrinsic::x86_sse42_pcmpestriz128: {
15817     unsigned Opcode;
15818     unsigned X86CC;
15819     switch (IntNo) {
15820     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15821     case Intrinsic::x86_sse42_pcmpistria128:
15822       Opcode = X86ISD::PCMPISTRI;
15823       X86CC = X86::COND_A;
15824       break;
15825     case Intrinsic::x86_sse42_pcmpestria128:
15826       Opcode = X86ISD::PCMPESTRI;
15827       X86CC = X86::COND_A;
15828       break;
15829     case Intrinsic::x86_sse42_pcmpistric128:
15830       Opcode = X86ISD::PCMPISTRI;
15831       X86CC = X86::COND_B;
15832       break;
15833     case Intrinsic::x86_sse42_pcmpestric128:
15834       Opcode = X86ISD::PCMPESTRI;
15835       X86CC = X86::COND_B;
15836       break;
15837     case Intrinsic::x86_sse42_pcmpistrio128:
15838       Opcode = X86ISD::PCMPISTRI;
15839       X86CC = X86::COND_O;
15840       break;
15841     case Intrinsic::x86_sse42_pcmpestrio128:
15842       Opcode = X86ISD::PCMPESTRI;
15843       X86CC = X86::COND_O;
15844       break;
15845     case Intrinsic::x86_sse42_pcmpistris128:
15846       Opcode = X86ISD::PCMPISTRI;
15847       X86CC = X86::COND_S;
15848       break;
15849     case Intrinsic::x86_sse42_pcmpestris128:
15850       Opcode = X86ISD::PCMPESTRI;
15851       X86CC = X86::COND_S;
15852       break;
15853     case Intrinsic::x86_sse42_pcmpistriz128:
15854       Opcode = X86ISD::PCMPISTRI;
15855       X86CC = X86::COND_E;
15856       break;
15857     case Intrinsic::x86_sse42_pcmpestriz128:
15858       Opcode = X86ISD::PCMPESTRI;
15859       X86CC = X86::COND_E;
15860       break;
15861     }
15862     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15863     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15864     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15865     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15866                                 DAG.getConstant(X86CC, dl, MVT::i8),
15867                                 SDValue(PCMP.getNode(), 1));
15868     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15869   }
15870
15871   case Intrinsic::x86_sse42_pcmpistri128:
15872   case Intrinsic::x86_sse42_pcmpestri128: {
15873     unsigned Opcode;
15874     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15875       Opcode = X86ISD::PCMPISTRI;
15876     else
15877       Opcode = X86ISD::PCMPESTRI;
15878
15879     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15880     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15881     return DAG.getNode(Opcode, dl, VTs, NewOps);
15882   }
15883
15884   case Intrinsic::x86_seh_lsda: {
15885     // Compute the symbol for the LSDA. We know it'll get emitted later.
15886     MachineFunction &MF = DAG.getMachineFunction();
15887     SDValue Op1 = Op.getOperand(1);
15888     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15889     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15890         GlobalValue::getRealLinkageName(Fn->getName()));
15891
15892     // Generate a simple absolute symbol reference. This intrinsic is only
15893     // supported on 32-bit Windows, which isn't PIC.
15894     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15895     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15896   }
15897
15898   case Intrinsic::x86_seh_recoverfp: {
15899     SDValue FnOp = Op.getOperand(1);
15900     SDValue IncomingFPOp = Op.getOperand(2);
15901     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15902     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15903     if (!Fn)
15904       report_fatal_error(
15905           "llvm.x86.seh.recoverfp must take a function as the first argument");
15906     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15907   }
15908
15909   case Intrinsic::localaddress: {
15910     // Returns one of the stack, base, or frame pointer registers, depending on
15911     // which is used to reference local variables.
15912     MachineFunction &MF = DAG.getMachineFunction();
15913     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15914     unsigned Reg;
15915     if (RegInfo->hasBasePointer(MF))
15916       Reg = RegInfo->getBaseRegister();
15917     else // This function handles the SP or FP case.
15918       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15919     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15920   }
15921   }
15922 }
15923
15924 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15925                               SDValue Src, SDValue Mask, SDValue Base,
15926                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15927                               const X86Subtarget * Subtarget) {
15928   SDLoc dl(Op);
15929   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15930   if (!C)
15931     llvm_unreachable("Invalid scale type");
15932   unsigned ScaleVal = C->getZExtValue();
15933   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15934     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15935
15936   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15937   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15938                              Index.getSimpleValueType().getVectorNumElements());
15939   SDValue MaskInReg;
15940   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15941   if (MaskC)
15942     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15943   else {
15944     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15945                                      Mask.getValueType().getSizeInBits());
15946
15947     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15948     // are extracted by EXTRACT_SUBVECTOR.
15949     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15950                             DAG.getBitcast(BitcastVT, Mask),
15951                             DAG.getIntPtrConstant(0, dl));
15952   }
15953   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15954   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15955   SDValue Segment = DAG.getRegister(0, MVT::i32);
15956   if (Src.getOpcode() == ISD::UNDEF)
15957     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15958   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15959   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15960   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15961   return DAG.getMergeValues(RetOps, dl);
15962 }
15963
15964 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15965                                SDValue Src, SDValue Mask, SDValue Base,
15966                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15967   SDLoc dl(Op);
15968   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15969   if (!C)
15970     llvm_unreachable("Invalid scale type");
15971   unsigned ScaleVal = C->getZExtValue();
15972   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15973     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15974
15975   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15976   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15977   SDValue Segment = DAG.getRegister(0, MVT::i32);
15978   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15979                              Index.getSimpleValueType().getVectorNumElements());
15980   SDValue MaskInReg;
15981   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15982   if (MaskC)
15983     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15984   else {
15985     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15986                                      Mask.getValueType().getSizeInBits());
15987
15988     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15989     // are extracted by EXTRACT_SUBVECTOR.
15990     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15991                             DAG.getBitcast(BitcastVT, Mask),
15992                             DAG.getIntPtrConstant(0, dl));
15993   }
15994   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15995   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15996   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15997   return SDValue(Res, 1);
15998 }
15999
16000 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16001                                SDValue Mask, SDValue Base, SDValue Index,
16002                                SDValue ScaleOp, SDValue Chain) {
16003   SDLoc dl(Op);
16004   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16005   assert(C && "Invalid scale type");
16006   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16007   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16008   SDValue Segment = DAG.getRegister(0, MVT::i32);
16009   EVT MaskVT =
16010     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16011   SDValue MaskInReg;
16012   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16013   if (MaskC)
16014     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16015   else
16016     MaskInReg = DAG.getBitcast(MaskVT, Mask);
16017   //SDVTList VTs = DAG.getVTList(MVT::Other);
16018   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16019   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16020   return SDValue(Res, 0);
16021 }
16022
16023 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16024 // read performance monitor counters (x86_rdpmc).
16025 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16026                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16027                               SmallVectorImpl<SDValue> &Results) {
16028   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16029   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16030   SDValue LO, HI;
16031
16032   // The ECX register is used to select the index of the performance counter
16033   // to read.
16034   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16035                                    N->getOperand(2));
16036   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16037
16038   // Reads the content of a 64-bit performance counter and returns it in the
16039   // registers EDX:EAX.
16040   if (Subtarget->is64Bit()) {
16041     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16042     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16043                             LO.getValue(2));
16044   } else {
16045     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16046     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16047                             LO.getValue(2));
16048   }
16049   Chain = HI.getValue(1);
16050
16051   if (Subtarget->is64Bit()) {
16052     // The EAX register is loaded with the low-order 32 bits. The EDX register
16053     // is loaded with the supported high-order bits of the counter.
16054     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16055                               DAG.getConstant(32, DL, MVT::i8));
16056     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16057     Results.push_back(Chain);
16058     return;
16059   }
16060
16061   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16062   SDValue Ops[] = { LO, HI };
16063   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16064   Results.push_back(Pair);
16065   Results.push_back(Chain);
16066 }
16067
16068 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16069 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16070 // also used to custom lower READCYCLECOUNTER nodes.
16071 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16072                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16073                               SmallVectorImpl<SDValue> &Results) {
16074   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16075   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16076   SDValue LO, HI;
16077
16078   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16079   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16080   // and the EAX register is loaded with the low-order 32 bits.
16081   if (Subtarget->is64Bit()) {
16082     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16083     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16084                             LO.getValue(2));
16085   } else {
16086     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16087     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16088                             LO.getValue(2));
16089   }
16090   SDValue Chain = HI.getValue(1);
16091
16092   if (Opcode == X86ISD::RDTSCP_DAG) {
16093     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16094
16095     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16096     // the ECX register. Add 'ecx' explicitly to the chain.
16097     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16098                                      HI.getValue(2));
16099     // Explicitly store the content of ECX at the location passed in input
16100     // to the 'rdtscp' intrinsic.
16101     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16102                          MachinePointerInfo(), false, false, 0);
16103   }
16104
16105   if (Subtarget->is64Bit()) {
16106     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16107     // the EAX register is loaded with the low-order 32 bits.
16108     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16109                               DAG.getConstant(32, DL, MVT::i8));
16110     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16111     Results.push_back(Chain);
16112     return;
16113   }
16114
16115   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16116   SDValue Ops[] = { LO, HI };
16117   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16118   Results.push_back(Pair);
16119   Results.push_back(Chain);
16120 }
16121
16122 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16123                                      SelectionDAG &DAG) {
16124   SmallVector<SDValue, 2> Results;
16125   SDLoc DL(Op);
16126   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16127                           Results);
16128   return DAG.getMergeValues(Results, DL);
16129 }
16130
16131 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16132                                     SelectionDAG &DAG) {
16133   MachineFunction &MF = DAG.getMachineFunction();
16134   const Function *Fn = MF.getFunction();
16135   SDLoc dl(Op);
16136   SDValue Chain = Op.getOperand(0);
16137
16138   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16139          "using llvm.x86.seh.restoreframe requires a frame pointer");
16140
16141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16142   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16143
16144   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16145   unsigned FrameReg =
16146       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16147   unsigned SPReg = RegInfo->getStackRegister();
16148   unsigned SlotSize = RegInfo->getSlotSize();
16149
16150   // Get incoming EBP.
16151   SDValue IncomingEBP =
16152       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16153
16154   // SP is saved in the first field of every registration node, so load
16155   // [EBP-RegNodeSize] into SP.
16156   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16157   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16158                                DAG.getConstant(-RegNodeSize, dl, VT));
16159   SDValue NewSP =
16160       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16161                   false, VT.getScalarSizeInBits() / 8);
16162   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16163
16164   if (!RegInfo->needsStackRealignment(MF)) {
16165     // Adjust EBP to point back to the original frame position.
16166     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16167     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16168   } else {
16169     assert(RegInfo->hasBasePointer(MF) &&
16170            "functions with Win32 EH must use frame or base pointer register");
16171
16172     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16173     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16174     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16175
16176     // Reload the spilled EBP value, now that the stack and base pointers are
16177     // set up.
16178     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16179     X86FI->setHasSEHFramePtrSave(true);
16180     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16181     X86FI->setSEHFramePtrSaveIndex(FI);
16182     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16183                                 MachinePointerInfo(), false, false, false,
16184                                 VT.getScalarSizeInBits() / 8);
16185     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16186   }
16187
16188   return Chain;
16189 }
16190
16191 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16192 /// return truncate Store/MaskedStore Node
16193 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16194                                                SelectionDAG &DAG,
16195                                                MVT ElementType) {
16196   SDLoc dl(Op);
16197   SDValue Mask = Op.getOperand(4);
16198   SDValue DataToTruncate = Op.getOperand(3);
16199   SDValue Addr = Op.getOperand(2);
16200   SDValue Chain = Op.getOperand(0);
16201
16202   EVT VT  = DataToTruncate.getValueType();
16203   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16204                              ElementType, VT.getVectorNumElements());
16205
16206   if (isAllOnes(Mask)) // return just a truncate store
16207     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16208                              MachinePointerInfo(), SVT, false, false,
16209                              SVT.getScalarSizeInBits()/8);
16210
16211   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16212                                 MVT::i1, VT.getVectorNumElements());
16213   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16214                                    Mask.getValueType().getSizeInBits());
16215   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16216   // are extracted by EXTRACT_SUBVECTOR.
16217   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16218                               DAG.getBitcast(BitcastVT, Mask),
16219                               DAG.getIntPtrConstant(0, dl));
16220
16221   MachineMemOperand *MMO = DAG.getMachineFunction().
16222     getMachineMemOperand(MachinePointerInfo(),
16223                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16224                          SVT.getScalarSizeInBits()/8);
16225
16226   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16227                             VMask, SVT, MMO, true);
16228 }
16229
16230 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16231                                       SelectionDAG &DAG) {
16232   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16233
16234   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16235   if (!IntrData) {
16236     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16237       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16238     return SDValue();
16239   }
16240
16241   SDLoc dl(Op);
16242   switch(IntrData->Type) {
16243   default:
16244     llvm_unreachable("Unknown Intrinsic Type");
16245     break;
16246   case RDSEED:
16247   case RDRAND: {
16248     // Emit the node with the right value type.
16249     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16250     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16251
16252     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16253     // Otherwise return the value from Rand, which is always 0, casted to i32.
16254     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16255                       DAG.getConstant(1, dl, Op->getValueType(1)),
16256                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16257                       SDValue(Result.getNode(), 1) };
16258     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16259                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16260                                   Ops);
16261
16262     // Return { result, isValid, chain }.
16263     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16264                        SDValue(Result.getNode(), 2));
16265   }
16266   case GATHER: {
16267   //gather(v1, mask, index, base, scale);
16268     SDValue Chain = Op.getOperand(0);
16269     SDValue Src   = Op.getOperand(2);
16270     SDValue Base  = Op.getOperand(3);
16271     SDValue Index = Op.getOperand(4);
16272     SDValue Mask  = Op.getOperand(5);
16273     SDValue Scale = Op.getOperand(6);
16274     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16275                          Chain, Subtarget);
16276   }
16277   case SCATTER: {
16278   //scatter(base, mask, index, v1, scale);
16279     SDValue Chain = Op.getOperand(0);
16280     SDValue Base  = Op.getOperand(2);
16281     SDValue Mask  = Op.getOperand(3);
16282     SDValue Index = Op.getOperand(4);
16283     SDValue Src   = Op.getOperand(5);
16284     SDValue Scale = Op.getOperand(6);
16285     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16286                           Scale, Chain);
16287   }
16288   case PREFETCH: {
16289     SDValue Hint = Op.getOperand(6);
16290     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16291     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16292     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16293     SDValue Chain = Op.getOperand(0);
16294     SDValue Mask  = Op.getOperand(2);
16295     SDValue Index = Op.getOperand(3);
16296     SDValue Base  = Op.getOperand(4);
16297     SDValue Scale = Op.getOperand(5);
16298     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16299   }
16300   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16301   case RDTSC: {
16302     SmallVector<SDValue, 2> Results;
16303     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16304                             Results);
16305     return DAG.getMergeValues(Results, dl);
16306   }
16307   // Read Performance Monitoring Counters.
16308   case RDPMC: {
16309     SmallVector<SDValue, 2> Results;
16310     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16311     return DAG.getMergeValues(Results, dl);
16312   }
16313   // XTEST intrinsics.
16314   case XTEST: {
16315     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16316     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16317     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16318                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16319                                 InTrans);
16320     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16321     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16322                        Ret, SDValue(InTrans.getNode(), 1));
16323   }
16324   // ADC/ADCX/SBB
16325   case ADX: {
16326     SmallVector<SDValue, 2> Results;
16327     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16328     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16329     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16330                                 DAG.getConstant(-1, dl, MVT::i8));
16331     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16332                               Op.getOperand(4), GenCF.getValue(1));
16333     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16334                                  Op.getOperand(5), MachinePointerInfo(),
16335                                  false, false, 0);
16336     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16337                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16338                                 Res.getValue(1));
16339     Results.push_back(SetCC);
16340     Results.push_back(Store);
16341     return DAG.getMergeValues(Results, dl);
16342   }
16343   case COMPRESS_TO_MEM: {
16344     SDLoc dl(Op);
16345     SDValue Mask = Op.getOperand(4);
16346     SDValue DataToCompress = Op.getOperand(3);
16347     SDValue Addr = Op.getOperand(2);
16348     SDValue Chain = Op.getOperand(0);
16349
16350     EVT VT = DataToCompress.getValueType();
16351     if (isAllOnes(Mask)) // return just a store
16352       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16353                           MachinePointerInfo(), false, false,
16354                           VT.getScalarSizeInBits()/8);
16355
16356     SDValue Compressed =
16357       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16358                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16359     return DAG.getStore(Chain, dl, Compressed, Addr,
16360                         MachinePointerInfo(), false, false,
16361                         VT.getScalarSizeInBits()/8);
16362   }
16363   case TRUNCATE_TO_MEM_VI8:
16364     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16365   case TRUNCATE_TO_MEM_VI16:
16366     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16367   case TRUNCATE_TO_MEM_VI32:
16368     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16369   case EXPAND_FROM_MEM: {
16370     SDLoc dl(Op);
16371     SDValue Mask = Op.getOperand(4);
16372     SDValue PassThru = Op.getOperand(3);
16373     SDValue Addr = Op.getOperand(2);
16374     SDValue Chain = Op.getOperand(0);
16375     EVT VT = Op.getValueType();
16376
16377     if (isAllOnes(Mask)) // return just a load
16378       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16379                          false, VT.getScalarSizeInBits()/8);
16380
16381     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16382                                        false, false, false,
16383                                        VT.getScalarSizeInBits()/8);
16384
16385     SDValue Results[] = {
16386       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16387                            Mask, PassThru, Subtarget, DAG), Chain};
16388     return DAG.getMergeValues(Results, dl);
16389   }
16390   }
16391 }
16392
16393 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16394                                            SelectionDAG &DAG) const {
16395   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16396   MFI->setReturnAddressIsTaken(true);
16397
16398   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16399     return SDValue();
16400
16401   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16402   SDLoc dl(Op);
16403   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16404
16405   if (Depth > 0) {
16406     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16407     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16408     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16409     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16410                        DAG.getNode(ISD::ADD, dl, PtrVT,
16411                                    FrameAddr, Offset),
16412                        MachinePointerInfo(), false, false, false, 0);
16413   }
16414
16415   // Just load the return address.
16416   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16417   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16418                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16419 }
16420
16421 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16422   MachineFunction &MF = DAG.getMachineFunction();
16423   MachineFrameInfo *MFI = MF.getFrameInfo();
16424   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16425   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16426   EVT VT = Op.getValueType();
16427
16428   MFI->setFrameAddressIsTaken(true);
16429
16430   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16431     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16432     // is not possible to crawl up the stack without looking at the unwind codes
16433     // simultaneously.
16434     int FrameAddrIndex = FuncInfo->getFAIndex();
16435     if (!FrameAddrIndex) {
16436       // Set up a frame object for the return address.
16437       unsigned SlotSize = RegInfo->getSlotSize();
16438       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16439           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16440       FuncInfo->setFAIndex(FrameAddrIndex);
16441     }
16442     return DAG.getFrameIndex(FrameAddrIndex, VT);
16443   }
16444
16445   unsigned FrameReg =
16446       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16447   SDLoc dl(Op);  // FIXME probably not meaningful
16448   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16449   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16450           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16451          "Invalid Frame Register!");
16452   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16453   while (Depth--)
16454     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16455                             MachinePointerInfo(),
16456                             false, false, false, 0);
16457   return FrameAddr;
16458 }
16459
16460 // FIXME? Maybe this could be a TableGen attribute on some registers and
16461 // this table could be generated automatically from RegInfo.
16462 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16463                                               SelectionDAG &DAG) const {
16464   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16465   const MachineFunction &MF = DAG.getMachineFunction();
16466
16467   unsigned Reg = StringSwitch<unsigned>(RegName)
16468                        .Case("esp", X86::ESP)
16469                        .Case("rsp", X86::RSP)
16470                        .Case("ebp", X86::EBP)
16471                        .Case("rbp", X86::RBP)
16472                        .Default(0);
16473
16474   if (Reg == X86::EBP || Reg == X86::RBP) {
16475     if (!TFI.hasFP(MF))
16476       report_fatal_error("register " + StringRef(RegName) +
16477                          " is allocatable: function has no frame pointer");
16478 #ifndef NDEBUG
16479     else {
16480       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16481       unsigned FrameReg =
16482           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16483       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16484              "Invalid Frame Register!");
16485     }
16486 #endif
16487   }
16488
16489   if (Reg)
16490     return Reg;
16491
16492   report_fatal_error("Invalid register name global variable");
16493 }
16494
16495 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16496                                                      SelectionDAG &DAG) const {
16497   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16498   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16499 }
16500
16501 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16502   SDValue Chain     = Op.getOperand(0);
16503   SDValue Offset    = Op.getOperand(1);
16504   SDValue Handler   = Op.getOperand(2);
16505   SDLoc dl      (Op);
16506
16507   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16508   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16509   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16510   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16511           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16512          "Invalid Frame Register!");
16513   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16514   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16515
16516   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16517                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16518                                                        dl));
16519   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16520   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16521                        false, false, 0);
16522   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16523
16524   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16525                      DAG.getRegister(StoreAddrReg, PtrVT));
16526 }
16527
16528 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16529                                                SelectionDAG &DAG) const {
16530   SDLoc DL(Op);
16531   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16532                      DAG.getVTList(MVT::i32, MVT::Other),
16533                      Op.getOperand(0), Op.getOperand(1));
16534 }
16535
16536 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16537                                                 SelectionDAG &DAG) const {
16538   SDLoc DL(Op);
16539   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16540                      Op.getOperand(0), Op.getOperand(1));
16541 }
16542
16543 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16544   return Op.getOperand(0);
16545 }
16546
16547 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16548                                                 SelectionDAG &DAG) const {
16549   SDValue Root = Op.getOperand(0);
16550   SDValue Trmp = Op.getOperand(1); // trampoline
16551   SDValue FPtr = Op.getOperand(2); // nested function
16552   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16553   SDLoc dl (Op);
16554
16555   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16556   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16557
16558   if (Subtarget->is64Bit()) {
16559     SDValue OutChains[6];
16560
16561     // Large code-model.
16562     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16563     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16564
16565     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16566     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16567
16568     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16569
16570     // Load the pointer to the nested function into R11.
16571     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16572     SDValue Addr = Trmp;
16573     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16574                                 Addr, MachinePointerInfo(TrmpAddr),
16575                                 false, false, 0);
16576
16577     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16578                        DAG.getConstant(2, dl, MVT::i64));
16579     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16580                                 MachinePointerInfo(TrmpAddr, 2),
16581                                 false, false, 2);
16582
16583     // Load the 'nest' parameter value into R10.
16584     // R10 is specified in X86CallingConv.td
16585     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16586     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16587                        DAG.getConstant(10, dl, MVT::i64));
16588     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16589                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16590                                 false, false, 0);
16591
16592     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16593                        DAG.getConstant(12, dl, MVT::i64));
16594     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16595                                 MachinePointerInfo(TrmpAddr, 12),
16596                                 false, false, 2);
16597
16598     // Jump to the nested function.
16599     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16600     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16601                        DAG.getConstant(20, dl, MVT::i64));
16602     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16603                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16604                                 false, false, 0);
16605
16606     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16607     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16608                        DAG.getConstant(22, dl, MVT::i64));
16609     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16610                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16611                                 false, false, 0);
16612
16613     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16614   } else {
16615     const Function *Func =
16616       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16617     CallingConv::ID CC = Func->getCallingConv();
16618     unsigned NestReg;
16619
16620     switch (CC) {
16621     default:
16622       llvm_unreachable("Unsupported calling convention");
16623     case CallingConv::C:
16624     case CallingConv::X86_StdCall: {
16625       // Pass 'nest' parameter in ECX.
16626       // Must be kept in sync with X86CallingConv.td
16627       NestReg = X86::ECX;
16628
16629       // Check that ECX wasn't needed by an 'inreg' parameter.
16630       FunctionType *FTy = Func->getFunctionType();
16631       const AttributeSet &Attrs = Func->getAttributes();
16632
16633       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16634         unsigned InRegCount = 0;
16635         unsigned Idx = 1;
16636
16637         for (FunctionType::param_iterator I = FTy->param_begin(),
16638              E = FTy->param_end(); I != E; ++I, ++Idx)
16639           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16640             auto &DL = DAG.getDataLayout();
16641             // FIXME: should only count parameters that are lowered to integers.
16642             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16643           }
16644
16645         if (InRegCount > 2) {
16646           report_fatal_error("Nest register in use - reduce number of inreg"
16647                              " parameters!");
16648         }
16649       }
16650       break;
16651     }
16652     case CallingConv::X86_FastCall:
16653     case CallingConv::X86_ThisCall:
16654     case CallingConv::Fast:
16655       // Pass 'nest' parameter in EAX.
16656       // Must be kept in sync with X86CallingConv.td
16657       NestReg = X86::EAX;
16658       break;
16659     }
16660
16661     SDValue OutChains[4];
16662     SDValue Addr, Disp;
16663
16664     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16665                        DAG.getConstant(10, dl, MVT::i32));
16666     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16667
16668     // This is storing the opcode for MOV32ri.
16669     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16670     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16671     OutChains[0] = DAG.getStore(Root, dl,
16672                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16673                                 Trmp, MachinePointerInfo(TrmpAddr),
16674                                 false, false, 0);
16675
16676     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16677                        DAG.getConstant(1, dl, MVT::i32));
16678     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16679                                 MachinePointerInfo(TrmpAddr, 1),
16680                                 false, false, 1);
16681
16682     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16683     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16684                        DAG.getConstant(5, dl, MVT::i32));
16685     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16686                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16687                                 false, false, 1);
16688
16689     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16690                        DAG.getConstant(6, dl, MVT::i32));
16691     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16692                                 MachinePointerInfo(TrmpAddr, 6),
16693                                 false, false, 1);
16694
16695     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16696   }
16697 }
16698
16699 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16700                                             SelectionDAG &DAG) const {
16701   /*
16702    The rounding mode is in bits 11:10 of FPSR, and has the following
16703    settings:
16704      00 Round to nearest
16705      01 Round to -inf
16706      10 Round to +inf
16707      11 Round to 0
16708
16709   FLT_ROUNDS, on the other hand, expects the following:
16710     -1 Undefined
16711      0 Round to 0
16712      1 Round to nearest
16713      2 Round to +inf
16714      3 Round to -inf
16715
16716   To perform the conversion, we do:
16717     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16718   */
16719
16720   MachineFunction &MF = DAG.getMachineFunction();
16721   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16722   unsigned StackAlignment = TFI.getStackAlignment();
16723   MVT VT = Op.getSimpleValueType();
16724   SDLoc DL(Op);
16725
16726   // Save FP Control Word to stack slot
16727   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16728   SDValue StackSlot =
16729       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16730
16731   MachineMemOperand *MMO =
16732       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16733                               MachineMemOperand::MOStore, 2, 2);
16734
16735   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16736   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16737                                           DAG.getVTList(MVT::Other),
16738                                           Ops, MVT::i16, MMO);
16739
16740   // Load FP Control Word from stack slot
16741   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16742                             MachinePointerInfo(), false, false, false, 0);
16743
16744   // Transform as necessary
16745   SDValue CWD1 =
16746     DAG.getNode(ISD::SRL, DL, MVT::i16,
16747                 DAG.getNode(ISD::AND, DL, MVT::i16,
16748                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16749                 DAG.getConstant(11, DL, MVT::i8));
16750   SDValue CWD2 =
16751     DAG.getNode(ISD::SRL, DL, MVT::i16,
16752                 DAG.getNode(ISD::AND, DL, MVT::i16,
16753                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16754                 DAG.getConstant(9, DL, MVT::i8));
16755
16756   SDValue RetVal =
16757     DAG.getNode(ISD::AND, DL, MVT::i16,
16758                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16759                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16760                             DAG.getConstant(1, DL, MVT::i16)),
16761                 DAG.getConstant(3, DL, MVT::i16));
16762
16763   return DAG.getNode((VT.getSizeInBits() < 16 ?
16764                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16765 }
16766
16767 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16768   MVT VT = Op.getSimpleValueType();
16769   EVT OpVT = VT;
16770   unsigned NumBits = VT.getSizeInBits();
16771   SDLoc dl(Op);
16772
16773   Op = Op.getOperand(0);
16774   if (VT == MVT::i8) {
16775     // Zero extend to i32 since there is not an i8 bsr.
16776     OpVT = MVT::i32;
16777     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16778   }
16779
16780   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16781   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16782   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16783
16784   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16785   SDValue Ops[] = {
16786     Op,
16787     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16788     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16789     Op.getValue(1)
16790   };
16791   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16792
16793   // Finally xor with NumBits-1.
16794   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16795                    DAG.getConstant(NumBits - 1, dl, OpVT));
16796
16797   if (VT == MVT::i8)
16798     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16799   return Op;
16800 }
16801
16802 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16803   MVT VT = Op.getSimpleValueType();
16804   EVT OpVT = VT;
16805   unsigned NumBits = VT.getSizeInBits();
16806   SDLoc dl(Op);
16807
16808   Op = Op.getOperand(0);
16809   if (VT == MVT::i8) {
16810     // Zero extend to i32 since there is not an i8 bsr.
16811     OpVT = MVT::i32;
16812     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16813   }
16814
16815   // Issue a bsr (scan bits in reverse).
16816   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16817   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16818
16819   // And xor with NumBits-1.
16820   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16821                    DAG.getConstant(NumBits - 1, dl, OpVT));
16822
16823   if (VT == MVT::i8)
16824     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16825   return Op;
16826 }
16827
16828 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16829   MVT VT = Op.getSimpleValueType();
16830   unsigned NumBits = VT.getSizeInBits();
16831   SDLoc dl(Op);
16832   Op = Op.getOperand(0);
16833
16834   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16835   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16836   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16837
16838   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16839   SDValue Ops[] = {
16840     Op,
16841     DAG.getConstant(NumBits, dl, VT),
16842     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16843     Op.getValue(1)
16844   };
16845   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16846 }
16847
16848 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16849 // ones, and then concatenate the result back.
16850 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16851   MVT VT = Op.getSimpleValueType();
16852
16853   assert(VT.is256BitVector() && VT.isInteger() &&
16854          "Unsupported value type for operation");
16855
16856   unsigned NumElems = VT.getVectorNumElements();
16857   SDLoc dl(Op);
16858
16859   // Extract the LHS vectors
16860   SDValue LHS = Op.getOperand(0);
16861   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16862   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16863
16864   // Extract the RHS vectors
16865   SDValue RHS = Op.getOperand(1);
16866   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16867   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16868
16869   MVT EltVT = VT.getVectorElementType();
16870   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16871
16872   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16873                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16874                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16875 }
16876
16877 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16878   if (Op.getValueType() == MVT::i1)
16879     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16880                        Op.getOperand(0), Op.getOperand(1));
16881   assert(Op.getSimpleValueType().is256BitVector() &&
16882          Op.getSimpleValueType().isInteger() &&
16883          "Only handle AVX 256-bit vector integer operation");
16884   return Lower256IntArith(Op, DAG);
16885 }
16886
16887 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16888   if (Op.getValueType() == MVT::i1)
16889     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16890                        Op.getOperand(0), Op.getOperand(1));
16891   assert(Op.getSimpleValueType().is256BitVector() &&
16892          Op.getSimpleValueType().isInteger() &&
16893          "Only handle AVX 256-bit vector integer operation");
16894   return Lower256IntArith(Op, DAG);
16895 }
16896
16897 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
16898   assert(Op.getSimpleValueType().is256BitVector() &&
16899          Op.getSimpleValueType().isInteger() &&
16900          "Only handle AVX 256-bit vector integer operation");
16901   return Lower256IntArith(Op, DAG);
16902 }
16903
16904 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16905                         SelectionDAG &DAG) {
16906   SDLoc dl(Op);
16907   MVT VT = Op.getSimpleValueType();
16908
16909   if (VT == MVT::i1)
16910     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16911
16912   // Decompose 256-bit ops into smaller 128-bit ops.
16913   if (VT.is256BitVector() && !Subtarget->hasInt256())
16914     return Lower256IntArith(Op, DAG);
16915
16916   SDValue A = Op.getOperand(0);
16917   SDValue B = Op.getOperand(1);
16918
16919   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16920   // pairs, multiply and truncate.
16921   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16922     if (Subtarget->hasInt256()) {
16923       if (VT == MVT::v32i8) {
16924         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16925         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16926         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16927         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16928         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16929         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16930         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16931         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16932                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16933                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16934       }
16935
16936       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16937       return DAG.getNode(
16938           ISD::TRUNCATE, dl, VT,
16939           DAG.getNode(ISD::MUL, dl, ExVT,
16940                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16941                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16942     }
16943
16944     assert(VT == MVT::v16i8 &&
16945            "Pre-AVX2 support only supports v16i8 multiplication");
16946     MVT ExVT = MVT::v8i16;
16947
16948     // Extract the lo parts and sign extend to i16
16949     SDValue ALo, BLo;
16950     if (Subtarget->hasSSE41()) {
16951       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16952       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16953     } else {
16954       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16955                               -1, 4, -1, 5, -1, 6, -1, 7};
16956       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16957       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16958       ALo = DAG.getBitcast(ExVT, ALo);
16959       BLo = DAG.getBitcast(ExVT, BLo);
16960       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16961       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16962     }
16963
16964     // Extract the hi parts and sign extend to i16
16965     SDValue AHi, BHi;
16966     if (Subtarget->hasSSE41()) {
16967       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16968                               -1, -1, -1, -1, -1, -1, -1, -1};
16969       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16970       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16971       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16972       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16973     } else {
16974       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16975                               -1, 12, -1, 13, -1, 14, -1, 15};
16976       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16977       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16978       AHi = DAG.getBitcast(ExVT, AHi);
16979       BHi = DAG.getBitcast(ExVT, BHi);
16980       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16981       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16982     }
16983
16984     // Multiply, mask the lower 8bits of the lo/hi results and pack
16985     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16986     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16987     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16988     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16989     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16990   }
16991
16992   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16993   if (VT == MVT::v4i32) {
16994     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16995            "Should not custom lower when pmuldq is available!");
16996
16997     // Extract the odd parts.
16998     static const int UnpackMask[] = { 1, -1, 3, -1 };
16999     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17000     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17001
17002     // Multiply the even parts.
17003     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17004     // Now multiply odd parts.
17005     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17006
17007     Evens = DAG.getBitcast(VT, Evens);
17008     Odds = DAG.getBitcast(VT, Odds);
17009
17010     // Merge the two vectors back together with a shuffle. This expands into 2
17011     // shuffles.
17012     static const int ShufMask[] = { 0, 4, 2, 6 };
17013     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17014   }
17015
17016   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17017          "Only know how to lower V2I64/V4I64/V8I64 multiply");
17018
17019   //  Ahi = psrlqi(a, 32);
17020   //  Bhi = psrlqi(b, 32);
17021   //
17022   //  AloBlo = pmuludq(a, b);
17023   //  AloBhi = pmuludq(a, Bhi);
17024   //  AhiBlo = pmuludq(Ahi, b);
17025
17026   //  AloBhi = psllqi(AloBhi, 32);
17027   //  AhiBlo = psllqi(AhiBlo, 32);
17028   //  return AloBlo + AloBhi + AhiBlo;
17029
17030   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17031   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17032
17033   SDValue AhiBlo = Ahi;
17034   SDValue AloBhi = Bhi;
17035   // Bit cast to 32-bit vectors for MULUDQ
17036   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17037                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17038   A = DAG.getBitcast(MulVT, A);
17039   B = DAG.getBitcast(MulVT, B);
17040   Ahi = DAG.getBitcast(MulVT, Ahi);
17041   Bhi = DAG.getBitcast(MulVT, Bhi);
17042
17043   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17044   // After shifting right const values the result may be all-zero.
17045   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17046     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17047     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17048   }
17049   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17050     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17051     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17052   }
17053
17054   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17055   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17056 }
17057
17058 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17059   assert(Subtarget->isTargetWin64() && "Unexpected target");
17060   EVT VT = Op.getValueType();
17061   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17062          "Unexpected return type for lowering");
17063
17064   RTLIB::Libcall LC;
17065   bool isSigned;
17066   switch (Op->getOpcode()) {
17067   default: llvm_unreachable("Unexpected request for libcall!");
17068   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17069   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17070   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17071   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17072   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17073   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17074   }
17075
17076   SDLoc dl(Op);
17077   SDValue InChain = DAG.getEntryNode();
17078
17079   TargetLowering::ArgListTy Args;
17080   TargetLowering::ArgListEntry Entry;
17081   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17082     EVT ArgVT = Op->getOperand(i).getValueType();
17083     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17084            "Unexpected argument type for lowering");
17085     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17086     Entry.Node = StackPtr;
17087     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17088                            false, false, 16);
17089     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17090     Entry.Ty = PointerType::get(ArgTy,0);
17091     Entry.isSExt = false;
17092     Entry.isZExt = false;
17093     Args.push_back(Entry);
17094   }
17095
17096   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17097                                          getPointerTy(DAG.getDataLayout()));
17098
17099   TargetLowering::CallLoweringInfo CLI(DAG);
17100   CLI.setDebugLoc(dl).setChain(InChain)
17101     .setCallee(getLibcallCallingConv(LC),
17102                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17103                Callee, std::move(Args), 0)
17104     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17105
17106   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17107   return DAG.getBitcast(VT, CallInfo.first);
17108 }
17109
17110 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17111                              SelectionDAG &DAG) {
17112   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17113   EVT VT = Op0.getValueType();
17114   SDLoc dl(Op);
17115
17116   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17117          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17118
17119   // PMULxD operations multiply each even value (starting at 0) of LHS with
17120   // the related value of RHS and produce a widen result.
17121   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17122   // => <2 x i64> <ae|cg>
17123   //
17124   // In other word, to have all the results, we need to perform two PMULxD:
17125   // 1. one with the even values.
17126   // 2. one with the odd values.
17127   // To achieve #2, with need to place the odd values at an even position.
17128   //
17129   // Place the odd value at an even position (basically, shift all values 1
17130   // step to the left):
17131   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17132   // <a|b|c|d> => <b|undef|d|undef>
17133   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17134   // <e|f|g|h> => <f|undef|h|undef>
17135   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17136
17137   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17138   // ints.
17139   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17140   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17141   unsigned Opcode =
17142       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17143   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17144   // => <2 x i64> <ae|cg>
17145   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17146   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17147   // => <2 x i64> <bf|dh>
17148   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17149
17150   // Shuffle it back into the right order.
17151   SDValue Highs, Lows;
17152   if (VT == MVT::v8i32) {
17153     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17154     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17155     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17156     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17157   } else {
17158     const int HighMask[] = {1, 5, 3, 7};
17159     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17160     const int LowMask[] = {0, 4, 2, 6};
17161     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17162   }
17163
17164   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17165   // unsigned multiply.
17166   if (IsSigned && !Subtarget->hasSSE41()) {
17167     SDValue ShAmt = DAG.getConstant(
17168         31, dl,
17169         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17170     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17171                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17172     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17173                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17174
17175     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17176     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17177   }
17178
17179   // The first result of MUL_LOHI is actually the low value, followed by the
17180   // high value.
17181   SDValue Ops[] = {Lows, Highs};
17182   return DAG.getMergeValues(Ops, dl);
17183 }
17184
17185 // Return true if the required (according to Opcode) shift-imm form is natively
17186 // supported by the Subtarget
17187 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17188                                         unsigned Opcode) {
17189   if (VT.getScalarSizeInBits() < 16)
17190     return false;
17191
17192   if (VT.is512BitVector() &&
17193       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17194     return true;
17195
17196   bool LShift = VT.is128BitVector() ||
17197     (VT.is256BitVector() && Subtarget->hasInt256());
17198
17199   bool AShift = LShift && (Subtarget->hasVLX() ||
17200     (VT != MVT::v2i64 && VT != MVT::v4i64));
17201   return (Opcode == ISD::SRA) ? AShift : LShift;
17202 }
17203
17204 // The shift amount is a variable, but it is the same for all vector lanes.
17205 // These instructions are defined together with shift-immediate.
17206 static
17207 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17208                                       unsigned Opcode) {
17209   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17210 }
17211
17212 // Return true if the required (according to Opcode) variable-shift form is
17213 // natively supported by the Subtarget
17214 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17215                                     unsigned Opcode) {
17216
17217   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17218     return false;
17219
17220   // vXi16 supported only on AVX-512, BWI
17221   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17222     return false;
17223
17224   if (VT.is512BitVector() || Subtarget->hasVLX())
17225     return true;
17226
17227   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17228   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17229   return (Opcode == ISD::SRA) ? AShift : LShift;
17230 }
17231
17232 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17233                                          const X86Subtarget *Subtarget) {
17234   MVT VT = Op.getSimpleValueType();
17235   SDLoc dl(Op);
17236   SDValue R = Op.getOperand(0);
17237   SDValue Amt = Op.getOperand(1);
17238
17239   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17240     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17241
17242   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17243     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17244     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17245     SDValue Ex = DAG.getBitcast(ExVT, R);
17246
17247     if (ShiftAmt >= 32) {
17248       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17249       SDValue Upper =
17250           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17251       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17252                                                  ShiftAmt - 32, DAG);
17253       if (VT == MVT::v2i64)
17254         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17255       if (VT == MVT::v4i64)
17256         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17257                                   {9, 1, 11, 3, 13, 5, 15, 7});
17258     } else {
17259       // SRA upper i32, SHL whole i64 and select lower i32.
17260       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17261                                                  ShiftAmt, DAG);
17262       SDValue Lower =
17263           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17264       Lower = DAG.getBitcast(ExVT, Lower);
17265       if (VT == MVT::v2i64)
17266         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17267       if (VT == MVT::v4i64)
17268         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17269                                   {8, 1, 10, 3, 12, 5, 14, 7});
17270     }
17271     return DAG.getBitcast(VT, Ex);
17272   };
17273
17274   // Optimize shl/srl/sra with constant shift amount.
17275   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17276     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17277       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17278
17279       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17280         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17281
17282       // i64 SRA needs to be performed as partial shifts.
17283       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17284           Op.getOpcode() == ISD::SRA)
17285         return ArithmeticShiftRight64(ShiftAmt);
17286
17287       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17288         unsigned NumElts = VT.getVectorNumElements();
17289         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17290
17291         if (Op.getOpcode() == ISD::SHL) {
17292           // Simple i8 add case
17293           if (ShiftAmt == 1)
17294             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17295
17296           // Make a large shift.
17297           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17298                                                    R, ShiftAmt, DAG);
17299           SHL = DAG.getBitcast(VT, SHL);
17300           // Zero out the rightmost bits.
17301           SmallVector<SDValue, 32> V(
17302               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17303           return DAG.getNode(ISD::AND, dl, VT, SHL,
17304                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17305         }
17306         if (Op.getOpcode() == ISD::SRL) {
17307           // Make a large shift.
17308           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17309                                                    R, ShiftAmt, DAG);
17310           SRL = DAG.getBitcast(VT, SRL);
17311           // Zero out the leftmost bits.
17312           SmallVector<SDValue, 32> V(
17313               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17314           return DAG.getNode(ISD::AND, dl, VT, SRL,
17315                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17316         }
17317         if (Op.getOpcode() == ISD::SRA) {
17318           if (ShiftAmt == 7) {
17319             // ashr(R, 7)  === cmp_slt(R, 0)
17320             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17321             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17322           }
17323
17324           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17325           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17326           SmallVector<SDValue, 32> V(NumElts,
17327                                      DAG.getConstant(128 >> ShiftAmt, dl,
17328                                                      MVT::i8));
17329           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17330           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17331           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17332           return Res;
17333         }
17334         llvm_unreachable("Unknown shift opcode.");
17335       }
17336     }
17337   }
17338
17339   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17340   if (!Subtarget->is64Bit() &&
17341       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17342
17343     // Peek through any splat that was introduced for i64 shift vectorization.
17344     int SplatIndex = -1;
17345     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17346       if (SVN->isSplat()) {
17347         SplatIndex = SVN->getSplatIndex();
17348         Amt = Amt.getOperand(0);
17349         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17350                "Splat shuffle referencing second operand");
17351       }
17352
17353     if (Amt.getOpcode() != ISD::BITCAST ||
17354         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17355       return SDValue();
17356
17357     Amt = Amt.getOperand(0);
17358     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17359                      VT.getVectorNumElements();
17360     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17361     uint64_t ShiftAmt = 0;
17362     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17363     for (unsigned i = 0; i != Ratio; ++i) {
17364       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17365       if (!C)
17366         return SDValue();
17367       // 6 == Log2(64)
17368       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17369     }
17370
17371     // Check remaining shift amounts (if not a splat).
17372     if (SplatIndex < 0) {
17373       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17374         uint64_t ShAmt = 0;
17375         for (unsigned j = 0; j != Ratio; ++j) {
17376           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17377           if (!C)
17378             return SDValue();
17379           // 6 == Log2(64)
17380           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17381         }
17382         if (ShAmt != ShiftAmt)
17383           return SDValue();
17384       }
17385     }
17386
17387     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17388       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17389
17390     if (Op.getOpcode() == ISD::SRA)
17391       return ArithmeticShiftRight64(ShiftAmt);
17392   }
17393
17394   return SDValue();
17395 }
17396
17397 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17398                                         const X86Subtarget* Subtarget) {
17399   MVT VT = Op.getSimpleValueType();
17400   SDLoc dl(Op);
17401   SDValue R = Op.getOperand(0);
17402   SDValue Amt = Op.getOperand(1);
17403
17404   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17405     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17406
17407   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17408     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17409
17410   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17411     SDValue BaseShAmt;
17412     EVT EltVT = VT.getVectorElementType();
17413
17414     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17415       // Check if this build_vector node is doing a splat.
17416       // If so, then set BaseShAmt equal to the splat value.
17417       BaseShAmt = BV->getSplatValue();
17418       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17419         BaseShAmt = SDValue();
17420     } else {
17421       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17422         Amt = Amt.getOperand(0);
17423
17424       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17425       if (SVN && SVN->isSplat()) {
17426         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17427         SDValue InVec = Amt.getOperand(0);
17428         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17429           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17430                  "Unexpected shuffle index found!");
17431           BaseShAmt = InVec.getOperand(SplatIdx);
17432         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17433            if (ConstantSDNode *C =
17434                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17435              if (C->getZExtValue() == SplatIdx)
17436                BaseShAmt = InVec.getOperand(1);
17437            }
17438         }
17439
17440         if (!BaseShAmt)
17441           // Avoid introducing an extract element from a shuffle.
17442           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17443                                   DAG.getIntPtrConstant(SplatIdx, dl));
17444       }
17445     }
17446
17447     if (BaseShAmt.getNode()) {
17448       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17449       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17450         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17451       else if (EltVT.bitsLT(MVT::i32))
17452         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17453
17454       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17455     }
17456   }
17457
17458   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17459   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17460       Amt.getOpcode() == ISD::BITCAST &&
17461       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17462     Amt = Amt.getOperand(0);
17463     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17464                      VT.getVectorNumElements();
17465     std::vector<SDValue> Vals(Ratio);
17466     for (unsigned i = 0; i != Ratio; ++i)
17467       Vals[i] = Amt.getOperand(i);
17468     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17469       for (unsigned j = 0; j != Ratio; ++j)
17470         if (Vals[j] != Amt.getOperand(i + j))
17471           return SDValue();
17472     }
17473
17474     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17475       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17476   }
17477   return SDValue();
17478 }
17479
17480 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17481                           SelectionDAG &DAG) {
17482   MVT VT = Op.getSimpleValueType();
17483   SDLoc dl(Op);
17484   SDValue R = Op.getOperand(0);
17485   SDValue Amt = Op.getOperand(1);
17486
17487   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17488   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17489
17490   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17491     return V;
17492
17493   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17494       return V;
17495
17496   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17497     return Op;
17498
17499   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17500   // shifts per-lane and then shuffle the partial results back together.
17501   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17502     // Splat the shift amounts so the scalar shifts above will catch it.
17503     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17504     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17505     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17506     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17507     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17508   }
17509
17510   // i64 vector arithmetic shift can be emulated with the transform:
17511   // M = lshr(SIGN_BIT, Amt)
17512   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17513   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17514       Op.getOpcode() == ISD::SRA) {
17515     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17516     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17517     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17518     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17519     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17520     return R;
17521   }
17522
17523   // If possible, lower this packed shift into a vector multiply instead of
17524   // expanding it into a sequence of scalar shifts.
17525   // Do this only if the vector shift count is a constant build_vector.
17526   if (Op.getOpcode() == ISD::SHL &&
17527       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17528        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17529       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17530     SmallVector<SDValue, 8> Elts;
17531     EVT SVT = VT.getScalarType();
17532     unsigned SVTBits = SVT.getSizeInBits();
17533     const APInt &One = APInt(SVTBits, 1);
17534     unsigned NumElems = VT.getVectorNumElements();
17535
17536     for (unsigned i=0; i !=NumElems; ++i) {
17537       SDValue Op = Amt->getOperand(i);
17538       if (Op->getOpcode() == ISD::UNDEF) {
17539         Elts.push_back(Op);
17540         continue;
17541       }
17542
17543       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17544       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17545       uint64_t ShAmt = C.getZExtValue();
17546       if (ShAmt >= SVTBits) {
17547         Elts.push_back(DAG.getUNDEF(SVT));
17548         continue;
17549       }
17550       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17551     }
17552     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17553     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17554   }
17555
17556   // Lower SHL with variable shift amount.
17557   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17558     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17559
17560     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17561                      DAG.getConstant(0x3f800000U, dl, VT));
17562     Op = DAG.getBitcast(MVT::v4f32, Op);
17563     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17564     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17565   }
17566
17567   // If possible, lower this shift as a sequence of two shifts by
17568   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17569   // Example:
17570   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17571   //
17572   // Could be rewritten as:
17573   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17574   //
17575   // The advantage is that the two shifts from the example would be
17576   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17577   // the vector shift into four scalar shifts plus four pairs of vector
17578   // insert/extract.
17579   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17580       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17581     unsigned TargetOpcode = X86ISD::MOVSS;
17582     bool CanBeSimplified;
17583     // The splat value for the first packed shift (the 'X' from the example).
17584     SDValue Amt1 = Amt->getOperand(0);
17585     // The splat value for the second packed shift (the 'Y' from the example).
17586     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17587                                         Amt->getOperand(2);
17588
17589     // See if it is possible to replace this node with a sequence of
17590     // two shifts followed by a MOVSS/MOVSD
17591     if (VT == MVT::v4i32) {
17592       // Check if it is legal to use a MOVSS.
17593       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17594                         Amt2 == Amt->getOperand(3);
17595       if (!CanBeSimplified) {
17596         // Otherwise, check if we can still simplify this node using a MOVSD.
17597         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17598                           Amt->getOperand(2) == Amt->getOperand(3);
17599         TargetOpcode = X86ISD::MOVSD;
17600         Amt2 = Amt->getOperand(2);
17601       }
17602     } else {
17603       // Do similar checks for the case where the machine value type
17604       // is MVT::v8i16.
17605       CanBeSimplified = Amt1 == Amt->getOperand(1);
17606       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17607         CanBeSimplified = Amt2 == Amt->getOperand(i);
17608
17609       if (!CanBeSimplified) {
17610         TargetOpcode = X86ISD::MOVSD;
17611         CanBeSimplified = true;
17612         Amt2 = Amt->getOperand(4);
17613         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17614           CanBeSimplified = Amt1 == Amt->getOperand(i);
17615         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17616           CanBeSimplified = Amt2 == Amt->getOperand(j);
17617       }
17618     }
17619
17620     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17621         isa<ConstantSDNode>(Amt2)) {
17622       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17623       EVT CastVT = MVT::v4i32;
17624       SDValue Splat1 =
17625         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17626       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17627       SDValue Splat2 =
17628         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17629       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17630       if (TargetOpcode == X86ISD::MOVSD)
17631         CastVT = MVT::v2i64;
17632       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17633       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17634       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17635                                             BitCast1, DAG);
17636       return DAG.getBitcast(VT, Result);
17637     }
17638   }
17639
17640   // v4i32 Non Uniform Shifts.
17641   // If the shift amount is constant we can shift each lane using the SSE2
17642   // immediate shifts, else we need to zero-extend each lane to the lower i64
17643   // and shift using the SSE2 variable shifts.
17644   // The separate results can then be blended together.
17645   if (VT == MVT::v4i32) {
17646     unsigned Opc = Op.getOpcode();
17647     SDValue Amt0, Amt1, Amt2, Amt3;
17648     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17649       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17650       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17651       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17652       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17653     } else {
17654       // ISD::SHL is handled above but we include it here for completeness.
17655       switch (Opc) {
17656       default:
17657         llvm_unreachable("Unknown target vector shift node");
17658       case ISD::SHL:
17659         Opc = X86ISD::VSHL;
17660         break;
17661       case ISD::SRL:
17662         Opc = X86ISD::VSRL;
17663         break;
17664       case ISD::SRA:
17665         Opc = X86ISD::VSRA;
17666         break;
17667       }
17668       // The SSE2 shifts use the lower i64 as the same shift amount for
17669       // all lanes and the upper i64 is ignored. These shuffle masks
17670       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17671       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17672       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17673       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17674       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17675       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17676     }
17677
17678     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17679     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17680     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17681     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17682     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17683     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17684     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17685   }
17686
17687   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17688     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17689     unsigned ShiftOpcode = Op->getOpcode();
17690
17691     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17692       // On SSE41 targets we make use of the fact that VSELECT lowers
17693       // to PBLENDVB which selects bytes based just on the sign bit.
17694       if (Subtarget->hasSSE41()) {
17695         V0 = DAG.getBitcast(VT, V0);
17696         V1 = DAG.getBitcast(VT, V1);
17697         Sel = DAG.getBitcast(VT, Sel);
17698         return DAG.getBitcast(SelVT,
17699                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17700       }
17701       // On pre-SSE41 targets we test for the sign bit by comparing to
17702       // zero - a negative value will set all bits of the lanes to true
17703       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17704       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17705       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17706       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17707     };
17708
17709     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17710     // We can safely do this using i16 shifts as we're only interested in
17711     // the 3 lower bits of each byte.
17712     Amt = DAG.getBitcast(ExtVT, Amt);
17713     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17714     Amt = DAG.getBitcast(VT, Amt);
17715
17716     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17717       // r = VSELECT(r, shift(r, 4), a);
17718       SDValue M =
17719           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17720       R = SignBitSelect(VT, Amt, M, R);
17721
17722       // a += a
17723       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17724
17725       // r = VSELECT(r, shift(r, 2), a);
17726       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17727       R = SignBitSelect(VT, Amt, M, R);
17728
17729       // a += a
17730       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17731
17732       // return VSELECT(r, shift(r, 1), a);
17733       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17734       R = SignBitSelect(VT, Amt, M, R);
17735       return R;
17736     }
17737
17738     if (Op->getOpcode() == ISD::SRA) {
17739       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17740       // so we can correctly sign extend. We don't care what happens to the
17741       // lower byte.
17742       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17743       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17744       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17745       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17746       ALo = DAG.getBitcast(ExtVT, ALo);
17747       AHi = DAG.getBitcast(ExtVT, AHi);
17748       RLo = DAG.getBitcast(ExtVT, RLo);
17749       RHi = DAG.getBitcast(ExtVT, RHi);
17750
17751       // r = VSELECT(r, shift(r, 4), a);
17752       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17753                                 DAG.getConstant(4, dl, ExtVT));
17754       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17755                                 DAG.getConstant(4, dl, ExtVT));
17756       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17757       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17758
17759       // a += a
17760       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17761       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17762
17763       // r = VSELECT(r, shift(r, 2), a);
17764       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17765                         DAG.getConstant(2, dl, ExtVT));
17766       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17767                         DAG.getConstant(2, dl, ExtVT));
17768       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17769       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17770
17771       // a += a
17772       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17773       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17774
17775       // r = VSELECT(r, shift(r, 1), a);
17776       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17777                         DAG.getConstant(1, dl, ExtVT));
17778       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17779                         DAG.getConstant(1, dl, ExtVT));
17780       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17781       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17782
17783       // Logical shift the result back to the lower byte, leaving a zero upper
17784       // byte
17785       // meaning that we can safely pack with PACKUSWB.
17786       RLo =
17787           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17788       RHi =
17789           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17790       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17791     }
17792   }
17793
17794   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17795   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17796   // solution better.
17797   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17798     MVT ExtVT = MVT::v8i32;
17799     unsigned ExtOpc =
17800         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17801     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17802     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17803     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17804                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17805   }
17806
17807   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17808     MVT ExtVT = MVT::v8i32;
17809     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17810     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17811     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17812     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17813     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17814     ALo = DAG.getBitcast(ExtVT, ALo);
17815     AHi = DAG.getBitcast(ExtVT, AHi);
17816     RLo = DAG.getBitcast(ExtVT, RLo);
17817     RHi = DAG.getBitcast(ExtVT, RHi);
17818     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17819     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17820     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17821     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17822     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17823   }
17824
17825   if (VT == MVT::v8i16) {
17826     unsigned ShiftOpcode = Op->getOpcode();
17827
17828     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17829       // On SSE41 targets we make use of the fact that VSELECT lowers
17830       // to PBLENDVB which selects bytes based just on the sign bit.
17831       if (Subtarget->hasSSE41()) {
17832         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17833         V0 = DAG.getBitcast(ExtVT, V0);
17834         V1 = DAG.getBitcast(ExtVT, V1);
17835         Sel = DAG.getBitcast(ExtVT, Sel);
17836         return DAG.getBitcast(
17837             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17838       }
17839       // On pre-SSE41 targets we splat the sign bit - a negative value will
17840       // set all bits of the lanes to true and VSELECT uses that in
17841       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17842       SDValue C =
17843           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17844       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17845     };
17846
17847     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17848     if (Subtarget->hasSSE41()) {
17849       // On SSE41 targets we need to replicate the shift mask in both
17850       // bytes for PBLENDVB.
17851       Amt = DAG.getNode(
17852           ISD::OR, dl, VT,
17853           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17854           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17855     } else {
17856       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17857     }
17858
17859     // r = VSELECT(r, shift(r, 8), a);
17860     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17861     R = SignBitSelect(Amt, M, R);
17862
17863     // a += a
17864     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17865
17866     // r = VSELECT(r, shift(r, 4), a);
17867     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17868     R = SignBitSelect(Amt, M, R);
17869
17870     // a += a
17871     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17872
17873     // r = VSELECT(r, shift(r, 2), a);
17874     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17875     R = SignBitSelect(Amt, M, R);
17876
17877     // a += a
17878     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17879
17880     // return VSELECT(r, shift(r, 1), a);
17881     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17882     R = SignBitSelect(Amt, M, R);
17883     return R;
17884   }
17885
17886   // Decompose 256-bit shifts into smaller 128-bit shifts.
17887   if (VT.is256BitVector()) {
17888     unsigned NumElems = VT.getVectorNumElements();
17889     MVT EltVT = VT.getVectorElementType();
17890     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17891
17892     // Extract the two vectors
17893     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17894     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17895
17896     // Recreate the shift amount vectors
17897     SDValue Amt1, Amt2;
17898     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17899       // Constant shift amount
17900       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17901       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17902       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17903
17904       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17905       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17906     } else {
17907       // Variable shift amount
17908       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17909       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17910     }
17911
17912     // Issue new vector shifts for the smaller types
17913     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17914     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17915
17916     // Concatenate the result back
17917     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17918   }
17919
17920   return SDValue();
17921 }
17922
17923 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17924   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17925   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17926   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17927   // has only one use.
17928   SDNode *N = Op.getNode();
17929   SDValue LHS = N->getOperand(0);
17930   SDValue RHS = N->getOperand(1);
17931   unsigned BaseOp = 0;
17932   unsigned Cond = 0;
17933   SDLoc DL(Op);
17934   switch (Op.getOpcode()) {
17935   default: llvm_unreachable("Unknown ovf instruction!");
17936   case ISD::SADDO:
17937     // A subtract of one will be selected as a INC. Note that INC doesn't
17938     // set CF, so we can't do this for UADDO.
17939     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17940       if (C->isOne()) {
17941         BaseOp = X86ISD::INC;
17942         Cond = X86::COND_O;
17943         break;
17944       }
17945     BaseOp = X86ISD::ADD;
17946     Cond = X86::COND_O;
17947     break;
17948   case ISD::UADDO:
17949     BaseOp = X86ISD::ADD;
17950     Cond = X86::COND_B;
17951     break;
17952   case ISD::SSUBO:
17953     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17954     // set CF, so we can't do this for USUBO.
17955     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17956       if (C->isOne()) {
17957         BaseOp = X86ISD::DEC;
17958         Cond = X86::COND_O;
17959         break;
17960       }
17961     BaseOp = X86ISD::SUB;
17962     Cond = X86::COND_O;
17963     break;
17964   case ISD::USUBO:
17965     BaseOp = X86ISD::SUB;
17966     Cond = X86::COND_B;
17967     break;
17968   case ISD::SMULO:
17969     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17970     Cond = X86::COND_O;
17971     break;
17972   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17973     if (N->getValueType(0) == MVT::i8) {
17974       BaseOp = X86ISD::UMUL8;
17975       Cond = X86::COND_O;
17976       break;
17977     }
17978     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17979                                  MVT::i32);
17980     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17981
17982     SDValue SetCC =
17983       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17984                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17985                   SDValue(Sum.getNode(), 2));
17986
17987     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17988   }
17989   }
17990
17991   // Also sets EFLAGS.
17992   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17993   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17994
17995   SDValue SetCC =
17996     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17997                 DAG.getConstant(Cond, DL, MVT::i32),
17998                 SDValue(Sum.getNode(), 1));
17999
18000   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18001 }
18002
18003 /// Returns true if the operand type is exactly twice the native width, and
18004 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18005 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18006 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18007 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18008   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18009
18010   if (OpWidth == 64)
18011     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18012   else if (OpWidth == 128)
18013     return Subtarget->hasCmpxchg16b();
18014   else
18015     return false;
18016 }
18017
18018 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18019   return needsCmpXchgNb(SI->getValueOperand()->getType());
18020 }
18021
18022 // Note: this turns large loads into lock cmpxchg8b/16b.
18023 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18024 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18025   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18026   return needsCmpXchgNb(PTy->getElementType());
18027 }
18028
18029 TargetLoweringBase::AtomicRMWExpansionKind
18030 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18031   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18032   Type *MemType = AI->getType();
18033
18034   // If the operand is too big, we must see if cmpxchg8/16b is available
18035   // and default to library calls otherwise.
18036   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18037     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18038                                    : AtomicRMWExpansionKind::None;
18039   }
18040
18041   AtomicRMWInst::BinOp Op = AI->getOperation();
18042   switch (Op) {
18043   default:
18044     llvm_unreachable("Unknown atomic operation");
18045   case AtomicRMWInst::Xchg:
18046   case AtomicRMWInst::Add:
18047   case AtomicRMWInst::Sub:
18048     // It's better to use xadd, xsub or xchg for these in all cases.
18049     return AtomicRMWExpansionKind::None;
18050   case AtomicRMWInst::Or:
18051   case AtomicRMWInst::And:
18052   case AtomicRMWInst::Xor:
18053     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18054     // prefix to a normal instruction for these operations.
18055     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18056                             : AtomicRMWExpansionKind::None;
18057   case AtomicRMWInst::Nand:
18058   case AtomicRMWInst::Max:
18059   case AtomicRMWInst::Min:
18060   case AtomicRMWInst::UMax:
18061   case AtomicRMWInst::UMin:
18062     // These always require a non-trivial set of data operations on x86. We must
18063     // use a cmpxchg loop.
18064     return AtomicRMWExpansionKind::CmpXChg;
18065   }
18066 }
18067
18068 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18069   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18070   // no-sse2). There isn't any reason to disable it if the target processor
18071   // supports it.
18072   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18073 }
18074
18075 LoadInst *
18076 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18077   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18078   Type *MemType = AI->getType();
18079   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18080   // there is no benefit in turning such RMWs into loads, and it is actually
18081   // harmful as it introduces a mfence.
18082   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18083     return nullptr;
18084
18085   auto Builder = IRBuilder<>(AI);
18086   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18087   auto SynchScope = AI->getSynchScope();
18088   // We must restrict the ordering to avoid generating loads with Release or
18089   // ReleaseAcquire orderings.
18090   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18091   auto Ptr = AI->getPointerOperand();
18092
18093   // Before the load we need a fence. Here is an example lifted from
18094   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18095   // is required:
18096   // Thread 0:
18097   //   x.store(1, relaxed);
18098   //   r1 = y.fetch_add(0, release);
18099   // Thread 1:
18100   //   y.fetch_add(42, acquire);
18101   //   r2 = x.load(relaxed);
18102   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18103   // lowered to just a load without a fence. A mfence flushes the store buffer,
18104   // making the optimization clearly correct.
18105   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18106   // otherwise, we might be able to be more aggressive on relaxed idempotent
18107   // rmw. In practice, they do not look useful, so we don't try to be
18108   // especially clever.
18109   if (SynchScope == SingleThread)
18110     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18111     // the IR level, so we must wrap it in an intrinsic.
18112     return nullptr;
18113
18114   if (!hasMFENCE(*Subtarget))
18115     // FIXME: it might make sense to use a locked operation here but on a
18116     // different cache-line to prevent cache-line bouncing. In practice it
18117     // is probably a small win, and x86 processors without mfence are rare
18118     // enough that we do not bother.
18119     return nullptr;
18120
18121   Function *MFence =
18122       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18123   Builder.CreateCall(MFence, {});
18124
18125   // Finally we can emit the atomic load.
18126   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18127           AI->getType()->getPrimitiveSizeInBits());
18128   Loaded->setAtomic(Order, SynchScope);
18129   AI->replaceAllUsesWith(Loaded);
18130   AI->eraseFromParent();
18131   return Loaded;
18132 }
18133
18134 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18135                                  SelectionDAG &DAG) {
18136   SDLoc dl(Op);
18137   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18138     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18139   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18140     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18141
18142   // The only fence that needs an instruction is a sequentially-consistent
18143   // cross-thread fence.
18144   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18145     if (hasMFENCE(*Subtarget))
18146       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18147
18148     SDValue Chain = Op.getOperand(0);
18149     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18150     SDValue Ops[] = {
18151       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18152       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18153       DAG.getRegister(0, MVT::i32),            // Index
18154       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18155       DAG.getRegister(0, MVT::i32),            // Segment.
18156       Zero,
18157       Chain
18158     };
18159     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18160     return SDValue(Res, 0);
18161   }
18162
18163   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18164   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18165 }
18166
18167 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18168                              SelectionDAG &DAG) {
18169   MVT T = Op.getSimpleValueType();
18170   SDLoc DL(Op);
18171   unsigned Reg = 0;
18172   unsigned size = 0;
18173   switch(T.SimpleTy) {
18174   default: llvm_unreachable("Invalid value type!");
18175   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18176   case MVT::i16: Reg = X86::AX;  size = 2; break;
18177   case MVT::i32: Reg = X86::EAX; size = 4; break;
18178   case MVT::i64:
18179     assert(Subtarget->is64Bit() && "Node not type legal!");
18180     Reg = X86::RAX; size = 8;
18181     break;
18182   }
18183   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18184                                   Op.getOperand(2), SDValue());
18185   SDValue Ops[] = { cpIn.getValue(0),
18186                     Op.getOperand(1),
18187                     Op.getOperand(3),
18188                     DAG.getTargetConstant(size, DL, MVT::i8),
18189                     cpIn.getValue(1) };
18190   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18191   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18192   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18193                                            Ops, T, MMO);
18194
18195   SDValue cpOut =
18196     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18197   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18198                                       MVT::i32, cpOut.getValue(2));
18199   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18200                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18201                                 EFLAGS);
18202
18203   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18204   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18205   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18206   return SDValue();
18207 }
18208
18209 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18210                             SelectionDAG &DAG) {
18211   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18212   MVT DstVT = Op.getSimpleValueType();
18213
18214   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18215     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18216     if (DstVT != MVT::f64)
18217       // This conversion needs to be expanded.
18218       return SDValue();
18219
18220     SDValue InVec = Op->getOperand(0);
18221     SDLoc dl(Op);
18222     unsigned NumElts = SrcVT.getVectorNumElements();
18223     EVT SVT = SrcVT.getVectorElementType();
18224
18225     // Widen the vector in input in the case of MVT::v2i32.
18226     // Example: from MVT::v2i32 to MVT::v4i32.
18227     SmallVector<SDValue, 16> Elts;
18228     for (unsigned i = 0, e = NumElts; i != e; ++i)
18229       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18230                                  DAG.getIntPtrConstant(i, dl)));
18231
18232     // Explicitly mark the extra elements as Undef.
18233     Elts.append(NumElts, DAG.getUNDEF(SVT));
18234
18235     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18236     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18237     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18238     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18239                        DAG.getIntPtrConstant(0, dl));
18240   }
18241
18242   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18243          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18244   assert((DstVT == MVT::i64 ||
18245           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18246          "Unexpected custom BITCAST");
18247   // i64 <=> MMX conversions are Legal.
18248   if (SrcVT==MVT::i64 && DstVT.isVector())
18249     return Op;
18250   if (DstVT==MVT::i64 && SrcVT.isVector())
18251     return Op;
18252   // MMX <=> MMX conversions are Legal.
18253   if (SrcVT.isVector() && DstVT.isVector())
18254     return Op;
18255   // All other conversions need to be expanded.
18256   return SDValue();
18257 }
18258
18259 /// Compute the horizontal sum of bytes in V for the elements of VT.
18260 ///
18261 /// Requires V to be a byte vector and VT to be an integer vector type with
18262 /// wider elements than V's type. The width of the elements of VT determines
18263 /// how many bytes of V are summed horizontally to produce each element of the
18264 /// result.
18265 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18266                                       const X86Subtarget *Subtarget,
18267                                       SelectionDAG &DAG) {
18268   SDLoc DL(V);
18269   MVT ByteVecVT = V.getSimpleValueType();
18270   MVT EltVT = VT.getVectorElementType();
18271   int NumElts = VT.getVectorNumElements();
18272   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18273          "Expected value to have byte element type.");
18274   assert(EltVT != MVT::i8 &&
18275          "Horizontal byte sum only makes sense for wider elements!");
18276   unsigned VecSize = VT.getSizeInBits();
18277   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18278
18279   // PSADBW instruction horizontally add all bytes and leave the result in i64
18280   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18281   if (EltVT == MVT::i64) {
18282     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18283     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18284     return DAG.getBitcast(VT, V);
18285   }
18286
18287   if (EltVT == MVT::i32) {
18288     // We unpack the low half and high half into i32s interleaved with zeros so
18289     // that we can use PSADBW to horizontally sum them. The most useful part of
18290     // this is that it lines up the results of two PSADBW instructions to be
18291     // two v2i64 vectors which concatenated are the 4 population counts. We can
18292     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18293     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18294     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18295     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18296
18297     // Do the horizontal sums into two v2i64s.
18298     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18299     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18300                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18301     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18302                        DAG.getBitcast(ByteVecVT, High), Zeros);
18303
18304     // Merge them together.
18305     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18306     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18307                     DAG.getBitcast(ShortVecVT, Low),
18308                     DAG.getBitcast(ShortVecVT, High));
18309
18310     return DAG.getBitcast(VT, V);
18311   }
18312
18313   // The only element type left is i16.
18314   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18315
18316   // To obtain pop count for each i16 element starting from the pop count for
18317   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18318   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18319   // directly supported.
18320   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18321   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18322   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18323   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18324                   DAG.getBitcast(ByteVecVT, V));
18325   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18326 }
18327
18328 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18329                                         const X86Subtarget *Subtarget,
18330                                         SelectionDAG &DAG) {
18331   MVT VT = Op.getSimpleValueType();
18332   MVT EltVT = VT.getVectorElementType();
18333   unsigned VecSize = VT.getSizeInBits();
18334
18335   // Implement a lookup table in register by using an algorithm based on:
18336   // http://wm.ite.pl/articles/sse-popcount.html
18337   //
18338   // The general idea is that every lower byte nibble in the input vector is an
18339   // index into a in-register pre-computed pop count table. We then split up the
18340   // input vector in two new ones: (1) a vector with only the shifted-right
18341   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18342   // masked out higher ones) for each byte. PSHUB is used separately with both
18343   // to index the in-register table. Next, both are added and the result is a
18344   // i8 vector where each element contains the pop count for input byte.
18345   //
18346   // To obtain the pop count for elements != i8, we follow up with the same
18347   // approach and use additional tricks as described below.
18348   //
18349   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18350                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18351                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18352                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18353
18354   int NumByteElts = VecSize / 8;
18355   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18356   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18357   SmallVector<SDValue, 16> LUTVec;
18358   for (int i = 0; i < NumByteElts; ++i)
18359     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18360   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18361   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18362                                   DAG.getConstant(0x0F, DL, MVT::i8));
18363   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18364
18365   // High nibbles
18366   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18367   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18368   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18369
18370   // Low nibbles
18371   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18372
18373   // The input vector is used as the shuffle mask that index elements into the
18374   // LUT. After counting low and high nibbles, add the vector to obtain the
18375   // final pop count per i8 element.
18376   SDValue HighPopCnt =
18377       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18378   SDValue LowPopCnt =
18379       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18380   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18381
18382   if (EltVT == MVT::i8)
18383     return PopCnt;
18384
18385   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18386 }
18387
18388 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18389                                        const X86Subtarget *Subtarget,
18390                                        SelectionDAG &DAG) {
18391   MVT VT = Op.getSimpleValueType();
18392   assert(VT.is128BitVector() &&
18393          "Only 128-bit vector bitmath lowering supported.");
18394
18395   int VecSize = VT.getSizeInBits();
18396   MVT EltVT = VT.getVectorElementType();
18397   int Len = EltVT.getSizeInBits();
18398
18399   // This is the vectorized version of the "best" algorithm from
18400   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18401   // with a minor tweak to use a series of adds + shifts instead of vector
18402   // multiplications. Implemented for all integer vector types. We only use
18403   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18404   // much faster, even faster than using native popcnt instructions.
18405
18406   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18407     MVT VT = V.getSimpleValueType();
18408     SmallVector<SDValue, 32> Shifters(
18409         VT.getVectorNumElements(),
18410         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18411     return DAG.getNode(OpCode, DL, VT, V,
18412                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18413   };
18414   auto GetMask = [&](SDValue V, APInt Mask) {
18415     MVT VT = V.getSimpleValueType();
18416     SmallVector<SDValue, 32> Masks(
18417         VT.getVectorNumElements(),
18418         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18419     return DAG.getNode(ISD::AND, DL, VT, V,
18420                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18421   };
18422
18423   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18424   // x86, so set the SRL type to have elements at least i16 wide. This is
18425   // correct because all of our SRLs are followed immediately by a mask anyways
18426   // that handles any bits that sneak into the high bits of the byte elements.
18427   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18428
18429   SDValue V = Op;
18430
18431   // v = v - ((v >> 1) & 0x55555555...)
18432   SDValue Srl =
18433       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18434   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18435   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18436
18437   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18438   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18439   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18440   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18441   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18442
18443   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18444   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18445   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18446   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18447
18448   // At this point, V contains the byte-wise population count, and we are
18449   // merely doing a horizontal sum if necessary to get the wider element
18450   // counts.
18451   if (EltVT == MVT::i8)
18452     return V;
18453
18454   return LowerHorizontalByteSum(
18455       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18456       DAG);
18457 }
18458
18459 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18460                                 SelectionDAG &DAG) {
18461   MVT VT = Op.getSimpleValueType();
18462   // FIXME: Need to add AVX-512 support here!
18463   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18464          "Unknown CTPOP type to handle");
18465   SDLoc DL(Op.getNode());
18466   SDValue Op0 = Op.getOperand(0);
18467
18468   if (!Subtarget->hasSSSE3()) {
18469     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18470     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18471     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18472   }
18473
18474   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18475     unsigned NumElems = VT.getVectorNumElements();
18476
18477     // Extract each 128-bit vector, compute pop count and concat the result.
18478     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18479     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18480
18481     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18482                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18483                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18484   }
18485
18486   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18487 }
18488
18489 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18490                           SelectionDAG &DAG) {
18491   assert(Op.getValueType().isVector() &&
18492          "We only do custom lowering for vector population count.");
18493   return LowerVectorCTPOP(Op, Subtarget, DAG);
18494 }
18495
18496 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18497   SDNode *Node = Op.getNode();
18498   SDLoc dl(Node);
18499   EVT T = Node->getValueType(0);
18500   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18501                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18502   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18503                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18504                        Node->getOperand(0),
18505                        Node->getOperand(1), negOp,
18506                        cast<AtomicSDNode>(Node)->getMemOperand(),
18507                        cast<AtomicSDNode>(Node)->getOrdering(),
18508                        cast<AtomicSDNode>(Node)->getSynchScope());
18509 }
18510
18511 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18512   SDNode *Node = Op.getNode();
18513   SDLoc dl(Node);
18514   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18515
18516   // Convert seq_cst store -> xchg
18517   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18518   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18519   //        (The only way to get a 16-byte store is cmpxchg16b)
18520   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18521   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18522       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18523     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18524                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18525                                  Node->getOperand(0),
18526                                  Node->getOperand(1), Node->getOperand(2),
18527                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18528                                  cast<AtomicSDNode>(Node)->getOrdering(),
18529                                  cast<AtomicSDNode>(Node)->getSynchScope());
18530     return Swap.getValue(1);
18531   }
18532   // Other atomic stores have a simple pattern.
18533   return Op;
18534 }
18535
18536 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18537   EVT VT = Op.getNode()->getSimpleValueType(0);
18538
18539   // Let legalize expand this if it isn't a legal type yet.
18540   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18541     return SDValue();
18542
18543   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18544
18545   unsigned Opc;
18546   bool ExtraOp = false;
18547   switch (Op.getOpcode()) {
18548   default: llvm_unreachable("Invalid code");
18549   case ISD::ADDC: Opc = X86ISD::ADD; break;
18550   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18551   case ISD::SUBC: Opc = X86ISD::SUB; break;
18552   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18553   }
18554
18555   if (!ExtraOp)
18556     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18557                        Op.getOperand(1));
18558   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18559                      Op.getOperand(1), Op.getOperand(2));
18560 }
18561
18562 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18563                             SelectionDAG &DAG) {
18564   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18565
18566   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18567   // which returns the values as { float, float } (in XMM0) or
18568   // { double, double } (which is returned in XMM0, XMM1).
18569   SDLoc dl(Op);
18570   SDValue Arg = Op.getOperand(0);
18571   EVT ArgVT = Arg.getValueType();
18572   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18573
18574   TargetLowering::ArgListTy Args;
18575   TargetLowering::ArgListEntry Entry;
18576
18577   Entry.Node = Arg;
18578   Entry.Ty = ArgTy;
18579   Entry.isSExt = false;
18580   Entry.isZExt = false;
18581   Args.push_back(Entry);
18582
18583   bool isF64 = ArgVT == MVT::f64;
18584   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18585   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18586   // the results are returned via SRet in memory.
18587   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18588   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18589   SDValue Callee =
18590       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18591
18592   Type *RetTy = isF64
18593     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18594     : (Type*)VectorType::get(ArgTy, 4);
18595
18596   TargetLowering::CallLoweringInfo CLI(DAG);
18597   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18598     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18599
18600   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18601
18602   if (isF64)
18603     // Returned in xmm0 and xmm1.
18604     return CallResult.first;
18605
18606   // Returned in bits 0:31 and 32:64 xmm0.
18607   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18608                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18609   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18610                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18611   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18612   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18613 }
18614
18615 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18616                              SelectionDAG &DAG) {
18617   assert(Subtarget->hasAVX512() &&
18618          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18619
18620   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18621   EVT VT = N->getValue().getValueType();
18622   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18623   SDLoc dl(Op);
18624
18625   // X86 scatter kills mask register, so its type should be added to
18626   // the list of return values
18627   if (N->getNumValues() == 1) {
18628     SDValue Index = N->getIndex();
18629     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18630         !Index.getValueType().is512BitVector())
18631       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18632
18633     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18634     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18635                       N->getOperand(3), Index };
18636
18637     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18638     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18639     return SDValue(NewScatter.getNode(), 0);
18640   }
18641   return Op;
18642 }
18643
18644 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18645                             SelectionDAG &DAG) {
18646   assert(Subtarget->hasAVX512() &&
18647          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18648
18649   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18650   EVT VT = Op.getValueType();
18651   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18652   SDLoc dl(Op);
18653
18654   SDValue Index = N->getIndex();
18655   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18656       !Index.getValueType().is512BitVector()) {
18657     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18658     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18659                       N->getOperand(3), Index };
18660     DAG.UpdateNodeOperands(N, Ops);
18661   }
18662   return Op;
18663 }
18664
18665 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18666                                                     SelectionDAG &DAG) const {
18667   // TODO: Eventually, the lowering of these nodes should be informed by or
18668   // deferred to the GC strategy for the function in which they appear. For
18669   // now, however, they must be lowered to something. Since they are logically
18670   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18671   // require special handling for these nodes), lower them as literal NOOPs for
18672   // the time being.
18673   SmallVector<SDValue, 2> Ops;
18674
18675   Ops.push_back(Op.getOperand(0));
18676   if (Op->getGluedNode())
18677     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18678
18679   SDLoc OpDL(Op);
18680   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18681   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18682
18683   return NOOP;
18684 }
18685
18686 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18687                                                   SelectionDAG &DAG) const {
18688   // TODO: Eventually, the lowering of these nodes should be informed by or
18689   // deferred to the GC strategy for the function in which they appear. For
18690   // now, however, they must be lowered to something. Since they are logically
18691   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18692   // require special handling for these nodes), lower them as literal NOOPs for
18693   // the time being.
18694   SmallVector<SDValue, 2> Ops;
18695
18696   Ops.push_back(Op.getOperand(0));
18697   if (Op->getGluedNode())
18698     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18699
18700   SDLoc OpDL(Op);
18701   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18702   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18703
18704   return NOOP;
18705 }
18706
18707 /// LowerOperation - Provide custom lowering hooks for some operations.
18708 ///
18709 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18710   switch (Op.getOpcode()) {
18711   default: llvm_unreachable("Should not custom lower this!");
18712   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18713   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18714     return LowerCMP_SWAP(Op, Subtarget, DAG);
18715   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18716   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18717   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18718   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18719   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18720   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18721   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18722   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18723   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18724   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18725   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18726   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18727   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18728   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18729   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18730   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18731   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18732   case ISD::SHL_PARTS:
18733   case ISD::SRA_PARTS:
18734   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18735   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18736   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18737   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18738   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18739   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18740   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18741   case ISD::SIGN_EXTEND_VECTOR_INREG:
18742     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18743   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18744   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18745   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18746   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18747   case ISD::FABS:
18748   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18749   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18750   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18751   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18752   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18753   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18754   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18755   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18756   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18757   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18758   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18759   case ISD::INTRINSIC_VOID:
18760   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18761   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18762   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18763   case ISD::FRAME_TO_ARGS_OFFSET:
18764                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18765   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18766   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18767   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18768   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18769   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18770   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18771   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18772   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18773   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18774   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18775   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18776   case ISD::UMUL_LOHI:
18777   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18778   case ISD::SRA:
18779   case ISD::SRL:
18780   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18781   case ISD::SADDO:
18782   case ISD::UADDO:
18783   case ISD::SSUBO:
18784   case ISD::USUBO:
18785   case ISD::SMULO:
18786   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18787   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18788   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18789   case ISD::ADDC:
18790   case ISD::ADDE:
18791   case ISD::SUBC:
18792   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18793   case ISD::ADD:                return LowerADD(Op, DAG);
18794   case ISD::SUB:                return LowerSUB(Op, DAG);
18795   case ISD::SMAX:
18796   case ISD::SMIN:
18797   case ISD::UMAX:
18798   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
18799   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18800   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18801   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18802   case ISD::GC_TRANSITION_START:
18803                                 return LowerGC_TRANSITION_START(Op, DAG);
18804   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18805   }
18806 }
18807
18808 /// ReplaceNodeResults - Replace a node with an illegal result type
18809 /// with a new node built out of custom code.
18810 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18811                                            SmallVectorImpl<SDValue>&Results,
18812                                            SelectionDAG &DAG) const {
18813   SDLoc dl(N);
18814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18815   switch (N->getOpcode()) {
18816   default:
18817     llvm_unreachable("Do not know how to custom type legalize this operation!");
18818   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18819   case X86ISD::FMINC:
18820   case X86ISD::FMIN:
18821   case X86ISD::FMAXC:
18822   case X86ISD::FMAX: {
18823     EVT VT = N->getValueType(0);
18824     if (VT != MVT::v2f32)
18825       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18826     SDValue UNDEF = DAG.getUNDEF(VT);
18827     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18828                               N->getOperand(0), UNDEF);
18829     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18830                               N->getOperand(1), UNDEF);
18831     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18832     return;
18833   }
18834   case ISD::SIGN_EXTEND_INREG:
18835   case ISD::ADDC:
18836   case ISD::ADDE:
18837   case ISD::SUBC:
18838   case ISD::SUBE:
18839     // We don't want to expand or promote these.
18840     return;
18841   case ISD::SDIV:
18842   case ISD::UDIV:
18843   case ISD::SREM:
18844   case ISD::UREM:
18845   case ISD::SDIVREM:
18846   case ISD::UDIVREM: {
18847     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18848     Results.push_back(V);
18849     return;
18850   }
18851   case ISD::FP_TO_SINT:
18852     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18853     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18854     if (N->getOperand(0).getValueType() == MVT::f16)
18855       break;
18856     // fallthrough
18857   case ISD::FP_TO_UINT: {
18858     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18859
18860     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18861       return;
18862
18863     std::pair<SDValue,SDValue> Vals =
18864         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18865     SDValue FIST = Vals.first, StackSlot = Vals.second;
18866     if (FIST.getNode()) {
18867       EVT VT = N->getValueType(0);
18868       // Return a load from the stack slot.
18869       if (StackSlot.getNode())
18870         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18871                                       MachinePointerInfo(),
18872                                       false, false, false, 0));
18873       else
18874         Results.push_back(FIST);
18875     }
18876     return;
18877   }
18878   case ISD::UINT_TO_FP: {
18879     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18880     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18881         N->getValueType(0) != MVT::v2f32)
18882       return;
18883     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18884                                  N->getOperand(0));
18885     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18886                                      MVT::f64);
18887     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18888     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18889                              DAG.getBitcast(MVT::v2i64, VBias));
18890     Or = DAG.getBitcast(MVT::v2f64, Or);
18891     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18892     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18893     return;
18894   }
18895   case ISD::FP_ROUND: {
18896     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18897         return;
18898     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18899     Results.push_back(V);
18900     return;
18901   }
18902   case ISD::FP_EXTEND: {
18903     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18904     // No other ValueType for FP_EXTEND should reach this point.
18905     assert(N->getValueType(0) == MVT::v2f32 &&
18906            "Do not know how to legalize this Node");
18907     return;
18908   }
18909   case ISD::INTRINSIC_W_CHAIN: {
18910     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18911     switch (IntNo) {
18912     default : llvm_unreachable("Do not know how to custom type "
18913                                "legalize this intrinsic operation!");
18914     case Intrinsic::x86_rdtsc:
18915       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18916                                      Results);
18917     case Intrinsic::x86_rdtscp:
18918       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18919                                      Results);
18920     case Intrinsic::x86_rdpmc:
18921       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18922     }
18923   }
18924   case ISD::READCYCLECOUNTER: {
18925     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18926                                    Results);
18927   }
18928   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18929     EVT T = N->getValueType(0);
18930     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18931     bool Regs64bit = T == MVT::i128;
18932     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18933     SDValue cpInL, cpInH;
18934     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18935                         DAG.getConstant(0, dl, HalfT));
18936     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18937                         DAG.getConstant(1, dl, HalfT));
18938     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18939                              Regs64bit ? X86::RAX : X86::EAX,
18940                              cpInL, SDValue());
18941     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18942                              Regs64bit ? X86::RDX : X86::EDX,
18943                              cpInH, cpInL.getValue(1));
18944     SDValue swapInL, swapInH;
18945     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18946                           DAG.getConstant(0, dl, HalfT));
18947     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18948                           DAG.getConstant(1, dl, HalfT));
18949     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18950                                Regs64bit ? X86::RBX : X86::EBX,
18951                                swapInL, cpInH.getValue(1));
18952     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18953                                Regs64bit ? X86::RCX : X86::ECX,
18954                                swapInH, swapInL.getValue(1));
18955     SDValue Ops[] = { swapInH.getValue(0),
18956                       N->getOperand(1),
18957                       swapInH.getValue(1) };
18958     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18959     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18960     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18961                                   X86ISD::LCMPXCHG8_DAG;
18962     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18963     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18964                                         Regs64bit ? X86::RAX : X86::EAX,
18965                                         HalfT, Result.getValue(1));
18966     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18967                                         Regs64bit ? X86::RDX : X86::EDX,
18968                                         HalfT, cpOutL.getValue(2));
18969     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18970
18971     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18972                                         MVT::i32, cpOutH.getValue(2));
18973     SDValue Success =
18974         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18975                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18976     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18977
18978     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18979     Results.push_back(Success);
18980     Results.push_back(EFLAGS.getValue(1));
18981     return;
18982   }
18983   case ISD::ATOMIC_SWAP:
18984   case ISD::ATOMIC_LOAD_ADD:
18985   case ISD::ATOMIC_LOAD_SUB:
18986   case ISD::ATOMIC_LOAD_AND:
18987   case ISD::ATOMIC_LOAD_OR:
18988   case ISD::ATOMIC_LOAD_XOR:
18989   case ISD::ATOMIC_LOAD_NAND:
18990   case ISD::ATOMIC_LOAD_MIN:
18991   case ISD::ATOMIC_LOAD_MAX:
18992   case ISD::ATOMIC_LOAD_UMIN:
18993   case ISD::ATOMIC_LOAD_UMAX:
18994   case ISD::ATOMIC_LOAD: {
18995     // Delegate to generic TypeLegalization. Situations we can really handle
18996     // should have already been dealt with by AtomicExpandPass.cpp.
18997     break;
18998   }
18999   case ISD::BITCAST: {
19000     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19001     EVT DstVT = N->getValueType(0);
19002     EVT SrcVT = N->getOperand(0)->getValueType(0);
19003
19004     if (SrcVT != MVT::f64 ||
19005         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19006       return;
19007
19008     unsigned NumElts = DstVT.getVectorNumElements();
19009     EVT SVT = DstVT.getVectorElementType();
19010     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19011     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19012                                    MVT::v2f64, N->getOperand(0));
19013     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19014
19015     if (ExperimentalVectorWideningLegalization) {
19016       // If we are legalizing vectors by widening, we already have the desired
19017       // legal vector type, just return it.
19018       Results.push_back(ToVecInt);
19019       return;
19020     }
19021
19022     SmallVector<SDValue, 8> Elts;
19023     for (unsigned i = 0, e = NumElts; i != e; ++i)
19024       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19025                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
19026
19027     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19028   }
19029   }
19030 }
19031
19032 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19033   switch ((X86ISD::NodeType)Opcode) {
19034   case X86ISD::FIRST_NUMBER:       break;
19035   case X86ISD::BSF:                return "X86ISD::BSF";
19036   case X86ISD::BSR:                return "X86ISD::BSR";
19037   case X86ISD::SHLD:               return "X86ISD::SHLD";
19038   case X86ISD::SHRD:               return "X86ISD::SHRD";
19039   case X86ISD::FAND:               return "X86ISD::FAND";
19040   case X86ISD::FANDN:              return "X86ISD::FANDN";
19041   case X86ISD::FOR:                return "X86ISD::FOR";
19042   case X86ISD::FXOR:               return "X86ISD::FXOR";
19043   case X86ISD::FILD:               return "X86ISD::FILD";
19044   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19045   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19046   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19047   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19048   case X86ISD::FLD:                return "X86ISD::FLD";
19049   case X86ISD::FST:                return "X86ISD::FST";
19050   case X86ISD::CALL:               return "X86ISD::CALL";
19051   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19052   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19053   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19054   case X86ISD::BT:                 return "X86ISD::BT";
19055   case X86ISD::CMP:                return "X86ISD::CMP";
19056   case X86ISD::COMI:               return "X86ISD::COMI";
19057   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19058   case X86ISD::CMPM:               return "X86ISD::CMPM";
19059   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19060   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19061   case X86ISD::SETCC:              return "X86ISD::SETCC";
19062   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19063   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19064   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19065   case X86ISD::CMOV:               return "X86ISD::CMOV";
19066   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19067   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19068   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19069   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19070   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19071   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19072   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19073   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19074   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19075   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19076   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19077   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19078   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19079   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19080   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19081   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19082   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19083   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19084   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19085   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19086   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19087   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19088   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19089   case X86ISD::HADD:               return "X86ISD::HADD";
19090   case X86ISD::HSUB:               return "X86ISD::HSUB";
19091   case X86ISD::FHADD:              return "X86ISD::FHADD";
19092   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19093   case X86ISD::ABS:                return "X86ISD::ABS";
19094   case X86ISD::FMAX:               return "X86ISD::FMAX";
19095   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19096   case X86ISD::FMIN:               return "X86ISD::FMIN";
19097   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19098   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19099   case X86ISD::FMINC:              return "X86ISD::FMINC";
19100   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19101   case X86ISD::FRCP:               return "X86ISD::FRCP";
19102   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19103   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19104   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19105   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19106   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19107   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19108   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19109   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19110   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19111   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19112   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19113   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19114   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19115   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19116   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19117   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19118   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19119   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19120   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19121   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19122   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19123   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19124   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19125   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19126   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19127   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19128   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19129   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19130   case X86ISD::VSHL:               return "X86ISD::VSHL";
19131   case X86ISD::VSRL:               return "X86ISD::VSRL";
19132   case X86ISD::VSRA:               return "X86ISD::VSRA";
19133   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19134   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19135   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19136   case X86ISD::CMPP:               return "X86ISD::CMPP";
19137   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19138   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19139   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19140   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19141   case X86ISD::ADD:                return "X86ISD::ADD";
19142   case X86ISD::SUB:                return "X86ISD::SUB";
19143   case X86ISD::ADC:                return "X86ISD::ADC";
19144   case X86ISD::SBB:                return "X86ISD::SBB";
19145   case X86ISD::SMUL:               return "X86ISD::SMUL";
19146   case X86ISD::UMUL:               return "X86ISD::UMUL";
19147   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19148   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19149   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19150   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19151   case X86ISD::INC:                return "X86ISD::INC";
19152   case X86ISD::DEC:                return "X86ISD::DEC";
19153   case X86ISD::OR:                 return "X86ISD::OR";
19154   case X86ISD::XOR:                return "X86ISD::XOR";
19155   case X86ISD::AND:                return "X86ISD::AND";
19156   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19157   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19158   case X86ISD::PTEST:              return "X86ISD::PTEST";
19159   case X86ISD::TESTP:              return "X86ISD::TESTP";
19160   case X86ISD::TESTM:              return "X86ISD::TESTM";
19161   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19162   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19163   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19164   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19165   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19166   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19167   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19168   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19169   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19170   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19171   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19172   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19173   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19174   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19175   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19176   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19177   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19178   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19179   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19180   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19181   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19182   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19183   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19184   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19185   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19186   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19187   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19188   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19189   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19190   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19191   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19192   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19193   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19194   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19195   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19196   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19197   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19198   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19199   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19200   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19201   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19202   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19203   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19204   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19205   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19206   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19207   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19208   case X86ISD::SAHF:               return "X86ISD::SAHF";
19209   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19210   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19211   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19212   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19213   case X86ISD::FMADD:              return "X86ISD::FMADD";
19214   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19215   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19216   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19217   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19218   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19219   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19220   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19221   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19222   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19223   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19224   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19225   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19226   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19227   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19228   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19229   case X86ISD::XTEST:              return "X86ISD::XTEST";
19230   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19231   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19232   case X86ISD::SELECT:             return "X86ISD::SELECT";
19233   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19234   case X86ISD::RCP28:              return "X86ISD::RCP28";
19235   case X86ISD::EXP2:               return "X86ISD::EXP2";
19236   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19237   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19238   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19239   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19240   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19241   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19242   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19243   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19244   case X86ISD::ADDS:               return "X86ISD::ADDS";
19245   case X86ISD::SUBS:               return "X86ISD::SUBS";
19246   case X86ISD::AVG:                return "X86ISD::AVG";
19247   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19248   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19249   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19250   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19251   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19252   }
19253   return nullptr;
19254 }
19255
19256 // isLegalAddressingMode - Return true if the addressing mode represented
19257 // by AM is legal for this target, for a load/store of the specified type.
19258 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19259                                               const AddrMode &AM, Type *Ty,
19260                                               unsigned AS) const {
19261   // X86 supports extremely general addressing modes.
19262   CodeModel::Model M = getTargetMachine().getCodeModel();
19263   Reloc::Model R = getTargetMachine().getRelocationModel();
19264
19265   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19266   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19267     return false;
19268
19269   if (AM.BaseGV) {
19270     unsigned GVFlags =
19271       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19272
19273     // If a reference to this global requires an extra load, we can't fold it.
19274     if (isGlobalStubReference(GVFlags))
19275       return false;
19276
19277     // If BaseGV requires a register for the PIC base, we cannot also have a
19278     // BaseReg specified.
19279     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19280       return false;
19281
19282     // If lower 4G is not available, then we must use rip-relative addressing.
19283     if ((M != CodeModel::Small || R != Reloc::Static) &&
19284         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19285       return false;
19286   }
19287
19288   switch (AM.Scale) {
19289   case 0:
19290   case 1:
19291   case 2:
19292   case 4:
19293   case 8:
19294     // These scales always work.
19295     break;
19296   case 3:
19297   case 5:
19298   case 9:
19299     // These scales are formed with basereg+scalereg.  Only accept if there is
19300     // no basereg yet.
19301     if (AM.HasBaseReg)
19302       return false;
19303     break;
19304   default:  // Other stuff never works.
19305     return false;
19306   }
19307
19308   return true;
19309 }
19310
19311 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19312   unsigned Bits = Ty->getScalarSizeInBits();
19313
19314   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19315   // particularly cheaper than those without.
19316   if (Bits == 8)
19317     return false;
19318
19319   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19320   // variable shifts just as cheap as scalar ones.
19321   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19322     return false;
19323
19324   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19325   // fully general vector.
19326   return true;
19327 }
19328
19329 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19330   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19331     return false;
19332   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19333   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19334   return NumBits1 > NumBits2;
19335 }
19336
19337 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19338   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19339     return false;
19340
19341   if (!isTypeLegal(EVT::getEVT(Ty1)))
19342     return false;
19343
19344   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19345
19346   // Assuming the caller doesn't have a zeroext or signext return parameter,
19347   // truncation all the way down to i1 is valid.
19348   return true;
19349 }
19350
19351 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19352   return isInt<32>(Imm);
19353 }
19354
19355 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19356   // Can also use sub to handle negated immediates.
19357   return isInt<32>(Imm);
19358 }
19359
19360 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19361   if (!VT1.isInteger() || !VT2.isInteger())
19362     return false;
19363   unsigned NumBits1 = VT1.getSizeInBits();
19364   unsigned NumBits2 = VT2.getSizeInBits();
19365   return NumBits1 > NumBits2;
19366 }
19367
19368 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19369   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19370   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19371 }
19372
19373 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19374   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19375   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19376 }
19377
19378 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19379   EVT VT1 = Val.getValueType();
19380   if (isZExtFree(VT1, VT2))
19381     return true;
19382
19383   if (Val.getOpcode() != ISD::LOAD)
19384     return false;
19385
19386   if (!VT1.isSimple() || !VT1.isInteger() ||
19387       !VT2.isSimple() || !VT2.isInteger())
19388     return false;
19389
19390   switch (VT1.getSimpleVT().SimpleTy) {
19391   default: break;
19392   case MVT::i8:
19393   case MVT::i16:
19394   case MVT::i32:
19395     // X86 has 8, 16, and 32-bit zero-extending loads.
19396     return true;
19397   }
19398
19399   return false;
19400 }
19401
19402 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19403
19404 bool
19405 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19406   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19407     return false;
19408
19409   VT = VT.getScalarType();
19410
19411   if (!VT.isSimple())
19412     return false;
19413
19414   switch (VT.getSimpleVT().SimpleTy) {
19415   case MVT::f32:
19416   case MVT::f64:
19417     return true;
19418   default:
19419     break;
19420   }
19421
19422   return false;
19423 }
19424
19425 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19426   // i16 instructions are longer (0x66 prefix) and potentially slower.
19427   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19428 }
19429
19430 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19431 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19432 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19433 /// are assumed to be legal.
19434 bool
19435 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19436                                       EVT VT) const {
19437   if (!VT.isSimple())
19438     return false;
19439
19440   // Not for i1 vectors
19441   if (VT.getScalarType() == MVT::i1)
19442     return false;
19443
19444   // Very little shuffling can be done for 64-bit vectors right now.
19445   if (VT.getSizeInBits() == 64)
19446     return false;
19447
19448   // We only care that the types being shuffled are legal. The lowering can
19449   // handle any possible shuffle mask that results.
19450   return isTypeLegal(VT.getSimpleVT());
19451 }
19452
19453 bool
19454 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19455                                           EVT VT) const {
19456   // Just delegate to the generic legality, clear masks aren't special.
19457   return isShuffleMaskLegal(Mask, VT);
19458 }
19459
19460 //===----------------------------------------------------------------------===//
19461 //                           X86 Scheduler Hooks
19462 //===----------------------------------------------------------------------===//
19463
19464 /// Utility function to emit xbegin specifying the start of an RTM region.
19465 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19466                                      const TargetInstrInfo *TII) {
19467   DebugLoc DL = MI->getDebugLoc();
19468
19469   const BasicBlock *BB = MBB->getBasicBlock();
19470   MachineFunction::iterator I = MBB;
19471   ++I;
19472
19473   // For the v = xbegin(), we generate
19474   //
19475   // thisMBB:
19476   //  xbegin sinkMBB
19477   //
19478   // mainMBB:
19479   //  eax = -1
19480   //
19481   // sinkMBB:
19482   //  v = eax
19483
19484   MachineBasicBlock *thisMBB = MBB;
19485   MachineFunction *MF = MBB->getParent();
19486   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19487   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19488   MF->insert(I, mainMBB);
19489   MF->insert(I, sinkMBB);
19490
19491   // Transfer the remainder of BB and its successor edges to sinkMBB.
19492   sinkMBB->splice(sinkMBB->begin(), MBB,
19493                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19494   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19495
19496   // thisMBB:
19497   //  xbegin sinkMBB
19498   //  # fallthrough to mainMBB
19499   //  # abortion to sinkMBB
19500   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19501   thisMBB->addSuccessor(mainMBB);
19502   thisMBB->addSuccessor(sinkMBB);
19503
19504   // mainMBB:
19505   //  EAX = -1
19506   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19507   mainMBB->addSuccessor(sinkMBB);
19508
19509   // sinkMBB:
19510   // EAX is live into the sinkMBB
19511   sinkMBB->addLiveIn(X86::EAX);
19512   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19513           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19514     .addReg(X86::EAX);
19515
19516   MI->eraseFromParent();
19517   return sinkMBB;
19518 }
19519
19520 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19521 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19522 // in the .td file.
19523 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19524                                        const TargetInstrInfo *TII) {
19525   unsigned Opc;
19526   switch (MI->getOpcode()) {
19527   default: llvm_unreachable("illegal opcode!");
19528   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19529   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19530   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19531   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19532   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19533   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19534   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19535   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19536   }
19537
19538   DebugLoc dl = MI->getDebugLoc();
19539   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19540
19541   unsigned NumArgs = MI->getNumOperands();
19542   for (unsigned i = 1; i < NumArgs; ++i) {
19543     MachineOperand &Op = MI->getOperand(i);
19544     if (!(Op.isReg() && Op.isImplicit()))
19545       MIB.addOperand(Op);
19546   }
19547   if (MI->hasOneMemOperand())
19548     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19549
19550   BuildMI(*BB, MI, dl,
19551     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19552     .addReg(X86::XMM0);
19553
19554   MI->eraseFromParent();
19555   return BB;
19556 }
19557
19558 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19559 // defs in an instruction pattern
19560 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19561                                        const TargetInstrInfo *TII) {
19562   unsigned Opc;
19563   switch (MI->getOpcode()) {
19564   default: llvm_unreachable("illegal opcode!");
19565   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19566   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19567   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19568   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19569   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19570   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19571   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19572   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19573   }
19574
19575   DebugLoc dl = MI->getDebugLoc();
19576   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19577
19578   unsigned NumArgs = MI->getNumOperands(); // remove the results
19579   for (unsigned i = 1; i < NumArgs; ++i) {
19580     MachineOperand &Op = MI->getOperand(i);
19581     if (!(Op.isReg() && Op.isImplicit()))
19582       MIB.addOperand(Op);
19583   }
19584   if (MI->hasOneMemOperand())
19585     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19586
19587   BuildMI(*BB, MI, dl,
19588     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19589     .addReg(X86::ECX);
19590
19591   MI->eraseFromParent();
19592   return BB;
19593 }
19594
19595 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19596                                       const X86Subtarget *Subtarget) {
19597   DebugLoc dl = MI->getDebugLoc();
19598   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19599   // Address into RAX/EAX, other two args into ECX, EDX.
19600   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19601   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19602   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19603   for (int i = 0; i < X86::AddrNumOperands; ++i)
19604     MIB.addOperand(MI->getOperand(i));
19605
19606   unsigned ValOps = X86::AddrNumOperands;
19607   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19608     .addReg(MI->getOperand(ValOps).getReg());
19609   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19610     .addReg(MI->getOperand(ValOps+1).getReg());
19611
19612   // The instruction doesn't actually take any operands though.
19613   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19614
19615   MI->eraseFromParent(); // The pseudo is gone now.
19616   return BB;
19617 }
19618
19619 MachineBasicBlock *
19620 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19621                                                  MachineBasicBlock *MBB) const {
19622   // Emit va_arg instruction on X86-64.
19623
19624   // Operands to this pseudo-instruction:
19625   // 0  ) Output        : destination address (reg)
19626   // 1-5) Input         : va_list address (addr, i64mem)
19627   // 6  ) ArgSize       : Size (in bytes) of vararg type
19628   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19629   // 8  ) Align         : Alignment of type
19630   // 9  ) EFLAGS (implicit-def)
19631
19632   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19633   static_assert(X86::AddrNumOperands == 5,
19634                 "VAARG_64 assumes 5 address operands");
19635
19636   unsigned DestReg = MI->getOperand(0).getReg();
19637   MachineOperand &Base = MI->getOperand(1);
19638   MachineOperand &Scale = MI->getOperand(2);
19639   MachineOperand &Index = MI->getOperand(3);
19640   MachineOperand &Disp = MI->getOperand(4);
19641   MachineOperand &Segment = MI->getOperand(5);
19642   unsigned ArgSize = MI->getOperand(6).getImm();
19643   unsigned ArgMode = MI->getOperand(7).getImm();
19644   unsigned Align = MI->getOperand(8).getImm();
19645
19646   // Memory Reference
19647   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19648   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19649   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19650
19651   // Machine Information
19652   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19653   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19654   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19655   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19656   DebugLoc DL = MI->getDebugLoc();
19657
19658   // struct va_list {
19659   //   i32   gp_offset
19660   //   i32   fp_offset
19661   //   i64   overflow_area (address)
19662   //   i64   reg_save_area (address)
19663   // }
19664   // sizeof(va_list) = 24
19665   // alignment(va_list) = 8
19666
19667   unsigned TotalNumIntRegs = 6;
19668   unsigned TotalNumXMMRegs = 8;
19669   bool UseGPOffset = (ArgMode == 1);
19670   bool UseFPOffset = (ArgMode == 2);
19671   unsigned MaxOffset = TotalNumIntRegs * 8 +
19672                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19673
19674   /* Align ArgSize to a multiple of 8 */
19675   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19676   bool NeedsAlign = (Align > 8);
19677
19678   MachineBasicBlock *thisMBB = MBB;
19679   MachineBasicBlock *overflowMBB;
19680   MachineBasicBlock *offsetMBB;
19681   MachineBasicBlock *endMBB;
19682
19683   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19684   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19685   unsigned OffsetReg = 0;
19686
19687   if (!UseGPOffset && !UseFPOffset) {
19688     // If we only pull from the overflow region, we don't create a branch.
19689     // We don't need to alter control flow.
19690     OffsetDestReg = 0; // unused
19691     OverflowDestReg = DestReg;
19692
19693     offsetMBB = nullptr;
19694     overflowMBB = thisMBB;
19695     endMBB = thisMBB;
19696   } else {
19697     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19698     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19699     // If not, pull from overflow_area. (branch to overflowMBB)
19700     //
19701     //       thisMBB
19702     //         |     .
19703     //         |        .
19704     //     offsetMBB   overflowMBB
19705     //         |        .
19706     //         |     .
19707     //        endMBB
19708
19709     // Registers for the PHI in endMBB
19710     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19711     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19712
19713     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19714     MachineFunction *MF = MBB->getParent();
19715     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19716     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19717     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19718
19719     MachineFunction::iterator MBBIter = MBB;
19720     ++MBBIter;
19721
19722     // Insert the new basic blocks
19723     MF->insert(MBBIter, offsetMBB);
19724     MF->insert(MBBIter, overflowMBB);
19725     MF->insert(MBBIter, endMBB);
19726
19727     // Transfer the remainder of MBB and its successor edges to endMBB.
19728     endMBB->splice(endMBB->begin(), thisMBB,
19729                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19730     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19731
19732     // Make offsetMBB and overflowMBB successors of thisMBB
19733     thisMBB->addSuccessor(offsetMBB);
19734     thisMBB->addSuccessor(overflowMBB);
19735
19736     // endMBB is a successor of both offsetMBB and overflowMBB
19737     offsetMBB->addSuccessor(endMBB);
19738     overflowMBB->addSuccessor(endMBB);
19739
19740     // Load the offset value into a register
19741     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19742     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19743       .addOperand(Base)
19744       .addOperand(Scale)
19745       .addOperand(Index)
19746       .addDisp(Disp, UseFPOffset ? 4 : 0)
19747       .addOperand(Segment)
19748       .setMemRefs(MMOBegin, MMOEnd);
19749
19750     // Check if there is enough room left to pull this argument.
19751     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19752       .addReg(OffsetReg)
19753       .addImm(MaxOffset + 8 - ArgSizeA8);
19754
19755     // Branch to "overflowMBB" if offset >= max
19756     // Fall through to "offsetMBB" otherwise
19757     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19758       .addMBB(overflowMBB);
19759   }
19760
19761   // In offsetMBB, emit code to use the reg_save_area.
19762   if (offsetMBB) {
19763     assert(OffsetReg != 0);
19764
19765     // Read the reg_save_area address.
19766     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19767     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19768       .addOperand(Base)
19769       .addOperand(Scale)
19770       .addOperand(Index)
19771       .addDisp(Disp, 16)
19772       .addOperand(Segment)
19773       .setMemRefs(MMOBegin, MMOEnd);
19774
19775     // Zero-extend the offset
19776     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19777       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19778         .addImm(0)
19779         .addReg(OffsetReg)
19780         .addImm(X86::sub_32bit);
19781
19782     // Add the offset to the reg_save_area to get the final address.
19783     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19784       .addReg(OffsetReg64)
19785       .addReg(RegSaveReg);
19786
19787     // Compute the offset for the next argument
19788     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19789     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19790       .addReg(OffsetReg)
19791       .addImm(UseFPOffset ? 16 : 8);
19792
19793     // Store it back into the va_list.
19794     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19795       .addOperand(Base)
19796       .addOperand(Scale)
19797       .addOperand(Index)
19798       .addDisp(Disp, UseFPOffset ? 4 : 0)
19799       .addOperand(Segment)
19800       .addReg(NextOffsetReg)
19801       .setMemRefs(MMOBegin, MMOEnd);
19802
19803     // Jump to endMBB
19804     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19805       .addMBB(endMBB);
19806   }
19807
19808   //
19809   // Emit code to use overflow area
19810   //
19811
19812   // Load the overflow_area address into a register.
19813   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19814   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19815     .addOperand(Base)
19816     .addOperand(Scale)
19817     .addOperand(Index)
19818     .addDisp(Disp, 8)
19819     .addOperand(Segment)
19820     .setMemRefs(MMOBegin, MMOEnd);
19821
19822   // If we need to align it, do so. Otherwise, just copy the address
19823   // to OverflowDestReg.
19824   if (NeedsAlign) {
19825     // Align the overflow address
19826     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19827     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19828
19829     // aligned_addr = (addr + (align-1)) & ~(align-1)
19830     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19831       .addReg(OverflowAddrReg)
19832       .addImm(Align-1);
19833
19834     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19835       .addReg(TmpReg)
19836       .addImm(~(uint64_t)(Align-1));
19837   } else {
19838     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19839       .addReg(OverflowAddrReg);
19840   }
19841
19842   // Compute the next overflow address after this argument.
19843   // (the overflow address should be kept 8-byte aligned)
19844   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19845   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19846     .addReg(OverflowDestReg)
19847     .addImm(ArgSizeA8);
19848
19849   // Store the new overflow address.
19850   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19851     .addOperand(Base)
19852     .addOperand(Scale)
19853     .addOperand(Index)
19854     .addDisp(Disp, 8)
19855     .addOperand(Segment)
19856     .addReg(NextAddrReg)
19857     .setMemRefs(MMOBegin, MMOEnd);
19858
19859   // If we branched, emit the PHI to the front of endMBB.
19860   if (offsetMBB) {
19861     BuildMI(*endMBB, endMBB->begin(), DL,
19862             TII->get(X86::PHI), DestReg)
19863       .addReg(OffsetDestReg).addMBB(offsetMBB)
19864       .addReg(OverflowDestReg).addMBB(overflowMBB);
19865   }
19866
19867   // Erase the pseudo instruction
19868   MI->eraseFromParent();
19869
19870   return endMBB;
19871 }
19872
19873 MachineBasicBlock *
19874 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19875                                                  MachineInstr *MI,
19876                                                  MachineBasicBlock *MBB) const {
19877   // Emit code to save XMM registers to the stack. The ABI says that the
19878   // number of registers to save is given in %al, so it's theoretically
19879   // possible to do an indirect jump trick to avoid saving all of them,
19880   // however this code takes a simpler approach and just executes all
19881   // of the stores if %al is non-zero. It's less code, and it's probably
19882   // easier on the hardware branch predictor, and stores aren't all that
19883   // expensive anyway.
19884
19885   // Create the new basic blocks. One block contains all the XMM stores,
19886   // and one block is the final destination regardless of whether any
19887   // stores were performed.
19888   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19889   MachineFunction *F = MBB->getParent();
19890   MachineFunction::iterator MBBIter = MBB;
19891   ++MBBIter;
19892   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19893   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19894   F->insert(MBBIter, XMMSaveMBB);
19895   F->insert(MBBIter, EndMBB);
19896
19897   // Transfer the remainder of MBB and its successor edges to EndMBB.
19898   EndMBB->splice(EndMBB->begin(), MBB,
19899                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19900   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19901
19902   // The original block will now fall through to the XMM save block.
19903   MBB->addSuccessor(XMMSaveMBB);
19904   // The XMMSaveMBB will fall through to the end block.
19905   XMMSaveMBB->addSuccessor(EndMBB);
19906
19907   // Now add the instructions.
19908   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19909   DebugLoc DL = MI->getDebugLoc();
19910
19911   unsigned CountReg = MI->getOperand(0).getReg();
19912   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19913   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19914
19915   if (!Subtarget->isTargetWin64()) {
19916     // If %al is 0, branch around the XMM save block.
19917     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19918     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19919     MBB->addSuccessor(EndMBB);
19920   }
19921
19922   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19923   // that was just emitted, but clearly shouldn't be "saved".
19924   assert((MI->getNumOperands() <= 3 ||
19925           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19926           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19927          && "Expected last argument to be EFLAGS");
19928   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19929   // In the XMM save block, save all the XMM argument registers.
19930   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19931     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19932     MachineMemOperand *MMO = F->getMachineMemOperand(
19933         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
19934         MachineMemOperand::MOStore,
19935         /*Size=*/16, /*Align=*/16);
19936     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19937       .addFrameIndex(RegSaveFrameIndex)
19938       .addImm(/*Scale=*/1)
19939       .addReg(/*IndexReg=*/0)
19940       .addImm(/*Disp=*/Offset)
19941       .addReg(/*Segment=*/0)
19942       .addReg(MI->getOperand(i).getReg())
19943       .addMemOperand(MMO);
19944   }
19945
19946   MI->eraseFromParent();   // The pseudo instruction is gone now.
19947
19948   return EndMBB;
19949 }
19950
19951 // The EFLAGS operand of SelectItr might be missing a kill marker
19952 // because there were multiple uses of EFLAGS, and ISel didn't know
19953 // which to mark. Figure out whether SelectItr should have had a
19954 // kill marker, and set it if it should. Returns the correct kill
19955 // marker value.
19956 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19957                                      MachineBasicBlock* BB,
19958                                      const TargetRegisterInfo* TRI) {
19959   // Scan forward through BB for a use/def of EFLAGS.
19960   MachineBasicBlock::iterator miI(std::next(SelectItr));
19961   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19962     const MachineInstr& mi = *miI;
19963     if (mi.readsRegister(X86::EFLAGS))
19964       return false;
19965     if (mi.definesRegister(X86::EFLAGS))
19966       break; // Should have kill-flag - update below.
19967   }
19968
19969   // If we hit the end of the block, check whether EFLAGS is live into a
19970   // successor.
19971   if (miI == BB->end()) {
19972     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19973                                           sEnd = BB->succ_end();
19974          sItr != sEnd; ++sItr) {
19975       MachineBasicBlock* succ = *sItr;
19976       if (succ->isLiveIn(X86::EFLAGS))
19977         return false;
19978     }
19979   }
19980
19981   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19982   // out. SelectMI should have a kill flag on EFLAGS.
19983   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19984   return true;
19985 }
19986
19987 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
19988 // together with other CMOV pseudo-opcodes into a single basic-block with
19989 // conditional jump around it.
19990 static bool isCMOVPseudo(MachineInstr *MI) {
19991   switch (MI->getOpcode()) {
19992   case X86::CMOV_FR32:
19993   case X86::CMOV_FR64:
19994   case X86::CMOV_GR8:
19995   case X86::CMOV_GR16:
19996   case X86::CMOV_GR32:
19997   case X86::CMOV_RFP32:
19998   case X86::CMOV_RFP64:
19999   case X86::CMOV_RFP80:
20000   case X86::CMOV_V2F64:
20001   case X86::CMOV_V2I64:
20002   case X86::CMOV_V4F32:
20003   case X86::CMOV_V4F64:
20004   case X86::CMOV_V4I64:
20005   case X86::CMOV_V16F32:
20006   case X86::CMOV_V8F32:
20007   case X86::CMOV_V8F64:
20008   case X86::CMOV_V8I64:
20009   case X86::CMOV_V8I1:
20010   case X86::CMOV_V16I1:
20011   case X86::CMOV_V32I1:
20012   case X86::CMOV_V64I1:
20013     return true;
20014
20015   default:
20016     return false;
20017   }
20018 }
20019
20020 MachineBasicBlock *
20021 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20022                                      MachineBasicBlock *BB) const {
20023   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20024   DebugLoc DL = MI->getDebugLoc();
20025
20026   // To "insert" a SELECT_CC instruction, we actually have to insert the
20027   // diamond control-flow pattern.  The incoming instruction knows the
20028   // destination vreg to set, the condition code register to branch on, the
20029   // true/false values to select between, and a branch opcode to use.
20030   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20031   MachineFunction::iterator It = BB;
20032   ++It;
20033
20034   //  thisMBB:
20035   //  ...
20036   //   TrueVal = ...
20037   //   cmpTY ccX, r1, r2
20038   //   bCC copy1MBB
20039   //   fallthrough --> copy0MBB
20040   MachineBasicBlock *thisMBB = BB;
20041   MachineFunction *F = BB->getParent();
20042
20043   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20044   // as described above, by inserting a BB, and then making a PHI at the join
20045   // point to select the true and false operands of the CMOV in the PHI.
20046   //
20047   // The code also handles two different cases of multiple CMOV opcodes
20048   // in a row.
20049   //
20050   // Case 1:
20051   // In this case, there are multiple CMOVs in a row, all which are based on
20052   // the same condition setting (or the exact opposite condition setting).
20053   // In this case we can lower all the CMOVs using a single inserted BB, and
20054   // then make a number of PHIs at the join point to model the CMOVs. The only
20055   // trickiness here, is that in a case like:
20056   //
20057   // t2 = CMOV cond1 t1, f1
20058   // t3 = CMOV cond1 t2, f2
20059   //
20060   // when rewriting this into PHIs, we have to perform some renaming on the
20061   // temps since you cannot have a PHI operand refer to a PHI result earlier
20062   // in the same block.  The "simple" but wrong lowering would be:
20063   //
20064   // t2 = PHI t1(BB1), f1(BB2)
20065   // t3 = PHI t2(BB1), f2(BB2)
20066   //
20067   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20068   // renaming is to note that on the path through BB1, t2 is really just a
20069   // copy of t1, and do that renaming, properly generating:
20070   //
20071   // t2 = PHI t1(BB1), f1(BB2)
20072   // t3 = PHI t1(BB1), f2(BB2)
20073   //
20074   // Case 2, we lower cascaded CMOVs such as
20075   //
20076   //   (CMOV (CMOV F, T, cc1), T, cc2)
20077   //
20078   // to two successives branches.  For that, we look for another CMOV as the
20079   // following instruction.
20080   //
20081   // Without this, we would add a PHI between the two jumps, which ends up
20082   // creating a few copies all around. For instance, for
20083   //
20084   //    (sitofp (zext (fcmp une)))
20085   //
20086   // we would generate:
20087   //
20088   //         ucomiss %xmm1, %xmm0
20089   //         movss  <1.0f>, %xmm0
20090   //         movaps  %xmm0, %xmm1
20091   //         jne     .LBB5_2
20092   //         xorps   %xmm1, %xmm1
20093   // .LBB5_2:
20094   //         jp      .LBB5_4
20095   //         movaps  %xmm1, %xmm0
20096   // .LBB5_4:
20097   //         retq
20098   //
20099   // because this custom-inserter would have generated:
20100   //
20101   //   A
20102   //   | \
20103   //   |  B
20104   //   | /
20105   //   C
20106   //   | \
20107   //   |  D
20108   //   | /
20109   //   E
20110   //
20111   // A: X = ...; Y = ...
20112   // B: empty
20113   // C: Z = PHI [X, A], [Y, B]
20114   // D: empty
20115   // E: PHI [X, C], [Z, D]
20116   //
20117   // If we lower both CMOVs in a single step, we can instead generate:
20118   //
20119   //   A
20120   //   | \
20121   //   |  C
20122   //   | /|
20123   //   |/ |
20124   //   |  |
20125   //   |  D
20126   //   | /
20127   //   E
20128   //
20129   // A: X = ...; Y = ...
20130   // D: empty
20131   // E: PHI [X, A], [X, C], [Y, D]
20132   //
20133   // Which, in our sitofp/fcmp example, gives us something like:
20134   //
20135   //         ucomiss %xmm1, %xmm0
20136   //         movss  <1.0f>, %xmm0
20137   //         jne     .LBB5_4
20138   //         jp      .LBB5_4
20139   //         xorps   %xmm0, %xmm0
20140   // .LBB5_4:
20141   //         retq
20142   //
20143   MachineInstr *CascadedCMOV = nullptr;
20144   MachineInstr *LastCMOV = MI;
20145   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20146   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20147   MachineBasicBlock::iterator NextMIIt =
20148       std::next(MachineBasicBlock::iterator(MI));
20149
20150   // Check for case 1, where there are multiple CMOVs with the same condition
20151   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20152   // number of jumps the most.
20153
20154   if (isCMOVPseudo(MI)) {
20155     // See if we have a string of CMOVS with the same condition.
20156     while (NextMIIt != BB->end() &&
20157            isCMOVPseudo(NextMIIt) &&
20158            (NextMIIt->getOperand(3).getImm() == CC ||
20159             NextMIIt->getOperand(3).getImm() == OppCC)) {
20160       LastCMOV = &*NextMIIt;
20161       ++NextMIIt;
20162     }
20163   }
20164
20165   // This checks for case 2, but only do this if we didn't already find
20166   // case 1, as indicated by LastCMOV == MI.
20167   if (LastCMOV == MI &&
20168       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20169       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20170       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20171     CascadedCMOV = &*NextMIIt;
20172   }
20173
20174   MachineBasicBlock *jcc1MBB = nullptr;
20175
20176   // If we have a cascaded CMOV, we lower it to two successive branches to
20177   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20178   if (CascadedCMOV) {
20179     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20180     F->insert(It, jcc1MBB);
20181     jcc1MBB->addLiveIn(X86::EFLAGS);
20182   }
20183
20184   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20185   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20186   F->insert(It, copy0MBB);
20187   F->insert(It, sinkMBB);
20188
20189   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20190   // live into the sink and copy blocks.
20191   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20192
20193   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20194   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20195       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20196     copy0MBB->addLiveIn(X86::EFLAGS);
20197     sinkMBB->addLiveIn(X86::EFLAGS);
20198   }
20199
20200   // Transfer the remainder of BB and its successor edges to sinkMBB.
20201   sinkMBB->splice(sinkMBB->begin(), BB,
20202                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20203   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20204
20205   // Add the true and fallthrough blocks as its successors.
20206   if (CascadedCMOV) {
20207     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20208     BB->addSuccessor(jcc1MBB);
20209
20210     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20211     // jump to the sinkMBB.
20212     jcc1MBB->addSuccessor(copy0MBB);
20213     jcc1MBB->addSuccessor(sinkMBB);
20214   } else {
20215     BB->addSuccessor(copy0MBB);
20216   }
20217
20218   // The true block target of the first (or only) branch is always sinkMBB.
20219   BB->addSuccessor(sinkMBB);
20220
20221   // Create the conditional branch instruction.
20222   unsigned Opc = X86::GetCondBranchFromCond(CC);
20223   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20224
20225   if (CascadedCMOV) {
20226     unsigned Opc2 = X86::GetCondBranchFromCond(
20227         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20228     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20229   }
20230
20231   //  copy0MBB:
20232   //   %FalseValue = ...
20233   //   # fallthrough to sinkMBB
20234   copy0MBB->addSuccessor(sinkMBB);
20235
20236   //  sinkMBB:
20237   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20238   //  ...
20239   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20240   MachineBasicBlock::iterator MIItEnd =
20241     std::next(MachineBasicBlock::iterator(LastCMOV));
20242   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20243   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20244   MachineInstrBuilder MIB;
20245
20246   // As we are creating the PHIs, we have to be careful if there is more than
20247   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20248   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20249   // That also means that PHI construction must work forward from earlier to
20250   // later, and that the code must maintain a mapping from earlier PHI's
20251   // destination registers, and the registers that went into the PHI.
20252
20253   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20254     unsigned DestReg = MIIt->getOperand(0).getReg();
20255     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20256     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20257
20258     // If this CMOV we are generating is the opposite condition from
20259     // the jump we generated, then we have to swap the operands for the
20260     // PHI that is going to be generated.
20261     if (MIIt->getOperand(3).getImm() == OppCC)
20262         std::swap(Op1Reg, Op2Reg);
20263
20264     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20265       Op1Reg = RegRewriteTable[Op1Reg].first;
20266
20267     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20268       Op2Reg = RegRewriteTable[Op2Reg].second;
20269
20270     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20271                   TII->get(X86::PHI), DestReg)
20272           .addReg(Op1Reg).addMBB(copy0MBB)
20273           .addReg(Op2Reg).addMBB(thisMBB);
20274
20275     // Add this PHI to the rewrite table.
20276     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20277   }
20278
20279   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20280   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20281   if (CascadedCMOV) {
20282     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20283     // Copy the PHI result to the register defined by the second CMOV.
20284     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20285             DL, TII->get(TargetOpcode::COPY),
20286             CascadedCMOV->getOperand(0).getReg())
20287         .addReg(MI->getOperand(0).getReg());
20288     CascadedCMOV->eraseFromParent();
20289   }
20290
20291   // Now remove the CMOV(s).
20292   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20293     (MIIt++)->eraseFromParent();
20294
20295   return sinkMBB;
20296 }
20297
20298 MachineBasicBlock *
20299 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20300                                        MachineBasicBlock *BB) const {
20301   // Combine the following atomic floating-point modification pattern:
20302   //   a.store(reg OP a.load(acquire), release)
20303   // Transform them into:
20304   //   OPss (%gpr), %xmm
20305   //   movss %xmm, (%gpr)
20306   // Or sd equivalent for 64-bit operations.
20307   unsigned MOp, FOp;
20308   switch (MI->getOpcode()) {
20309   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20310   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20311   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20312   }
20313   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20314   DebugLoc DL = MI->getDebugLoc();
20315   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20316   unsigned MSrc = MI->getOperand(0).getReg();
20317   unsigned VSrc = MI->getOperand(5).getReg();
20318   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20319                                 .addReg(/*Base=*/MSrc)
20320                                 .addImm(/*Scale=*/1)
20321                                 .addReg(/*Index=*/0)
20322                                 .addImm(0)
20323                                 .addReg(0);
20324   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20325                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20326                           .addReg(VSrc)
20327                           .addReg(/*Base=*/MSrc)
20328                           .addImm(/*Scale=*/1)
20329                           .addReg(/*Index=*/0)
20330                           .addImm(/*Disp=*/0)
20331                           .addReg(/*Segment=*/0);
20332   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20333   MI->eraseFromParent(); // The pseudo instruction is gone now.
20334   return BB;
20335 }
20336
20337 MachineBasicBlock *
20338 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20339                                         MachineBasicBlock *BB) const {
20340   MachineFunction *MF = BB->getParent();
20341   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20342   DebugLoc DL = MI->getDebugLoc();
20343   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20344
20345   assert(MF->shouldSplitStack());
20346
20347   const bool Is64Bit = Subtarget->is64Bit();
20348   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20349
20350   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20351   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20352
20353   // BB:
20354   //  ... [Till the alloca]
20355   // If stacklet is not large enough, jump to mallocMBB
20356   //
20357   // bumpMBB:
20358   //  Allocate by subtracting from RSP
20359   //  Jump to continueMBB
20360   //
20361   // mallocMBB:
20362   //  Allocate by call to runtime
20363   //
20364   // continueMBB:
20365   //  ...
20366   //  [rest of original BB]
20367   //
20368
20369   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20370   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20371   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20372
20373   MachineRegisterInfo &MRI = MF->getRegInfo();
20374   const TargetRegisterClass *AddrRegClass =
20375       getRegClassFor(getPointerTy(MF->getDataLayout()));
20376
20377   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20378     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20379     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20380     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20381     sizeVReg = MI->getOperand(1).getReg(),
20382     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20383
20384   MachineFunction::iterator MBBIter = BB;
20385   ++MBBIter;
20386
20387   MF->insert(MBBIter, bumpMBB);
20388   MF->insert(MBBIter, mallocMBB);
20389   MF->insert(MBBIter, continueMBB);
20390
20391   continueMBB->splice(continueMBB->begin(), BB,
20392                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20393   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20394
20395   // Add code to the main basic block to check if the stack limit has been hit,
20396   // and if so, jump to mallocMBB otherwise to bumpMBB.
20397   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20398   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20399     .addReg(tmpSPVReg).addReg(sizeVReg);
20400   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20401     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20402     .addReg(SPLimitVReg);
20403   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20404
20405   // bumpMBB simply decreases the stack pointer, since we know the current
20406   // stacklet has enough space.
20407   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20408     .addReg(SPLimitVReg);
20409   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20410     .addReg(SPLimitVReg);
20411   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20412
20413   // Calls into a routine in libgcc to allocate more space from the heap.
20414   const uint32_t *RegMask =
20415       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20416   if (IsLP64) {
20417     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20418       .addReg(sizeVReg);
20419     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20420       .addExternalSymbol("__morestack_allocate_stack_space")
20421       .addRegMask(RegMask)
20422       .addReg(X86::RDI, RegState::Implicit)
20423       .addReg(X86::RAX, RegState::ImplicitDefine);
20424   } else if (Is64Bit) {
20425     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20426       .addReg(sizeVReg);
20427     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20428       .addExternalSymbol("__morestack_allocate_stack_space")
20429       .addRegMask(RegMask)
20430       .addReg(X86::EDI, RegState::Implicit)
20431       .addReg(X86::EAX, RegState::ImplicitDefine);
20432   } else {
20433     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20434       .addImm(12);
20435     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20436     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20437       .addExternalSymbol("__morestack_allocate_stack_space")
20438       .addRegMask(RegMask)
20439       .addReg(X86::EAX, RegState::ImplicitDefine);
20440   }
20441
20442   if (!Is64Bit)
20443     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20444       .addImm(16);
20445
20446   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20447     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20448   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20449
20450   // Set up the CFG correctly.
20451   BB->addSuccessor(bumpMBB);
20452   BB->addSuccessor(mallocMBB);
20453   mallocMBB->addSuccessor(continueMBB);
20454   bumpMBB->addSuccessor(continueMBB);
20455
20456   // Take care of the PHI nodes.
20457   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20458           MI->getOperand(0).getReg())
20459     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20460     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20461
20462   // Delete the original pseudo instruction.
20463   MI->eraseFromParent();
20464
20465   // And we're done.
20466   return continueMBB;
20467 }
20468
20469 MachineBasicBlock *
20470 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20471                                         MachineBasicBlock *BB) const {
20472   DebugLoc DL = MI->getDebugLoc();
20473
20474   assert(!Subtarget->isTargetMachO());
20475
20476   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20477                                                     DL);
20478
20479   MI->eraseFromParent();   // The pseudo instruction is gone now.
20480   return BB;
20481 }
20482
20483 MachineBasicBlock *
20484 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20485                                       MachineBasicBlock *BB) const {
20486   // This is pretty easy.  We're taking the value that we received from
20487   // our load from the relocation, sticking it in either RDI (x86-64)
20488   // or EAX and doing an indirect call.  The return value will then
20489   // be in the normal return register.
20490   MachineFunction *F = BB->getParent();
20491   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20492   DebugLoc DL = MI->getDebugLoc();
20493
20494   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20495   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20496
20497   // Get a register mask for the lowered call.
20498   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20499   // proper register mask.
20500   const uint32_t *RegMask =
20501       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20502   if (Subtarget->is64Bit()) {
20503     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20504                                       TII->get(X86::MOV64rm), X86::RDI)
20505     .addReg(X86::RIP)
20506     .addImm(0).addReg(0)
20507     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20508                       MI->getOperand(3).getTargetFlags())
20509     .addReg(0);
20510     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20511     addDirectMem(MIB, X86::RDI);
20512     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20513   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20514     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20515                                       TII->get(X86::MOV32rm), X86::EAX)
20516     .addReg(0)
20517     .addImm(0).addReg(0)
20518     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20519                       MI->getOperand(3).getTargetFlags())
20520     .addReg(0);
20521     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20522     addDirectMem(MIB, X86::EAX);
20523     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20524   } else {
20525     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20526                                       TII->get(X86::MOV32rm), X86::EAX)
20527     .addReg(TII->getGlobalBaseReg(F))
20528     .addImm(0).addReg(0)
20529     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20530                       MI->getOperand(3).getTargetFlags())
20531     .addReg(0);
20532     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20533     addDirectMem(MIB, X86::EAX);
20534     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20535   }
20536
20537   MI->eraseFromParent(); // The pseudo instruction is gone now.
20538   return BB;
20539 }
20540
20541 MachineBasicBlock *
20542 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20543                                     MachineBasicBlock *MBB) const {
20544   DebugLoc DL = MI->getDebugLoc();
20545   MachineFunction *MF = MBB->getParent();
20546   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20547   MachineRegisterInfo &MRI = MF->getRegInfo();
20548
20549   const BasicBlock *BB = MBB->getBasicBlock();
20550   MachineFunction::iterator I = MBB;
20551   ++I;
20552
20553   // Memory Reference
20554   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20555   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20556
20557   unsigned DstReg;
20558   unsigned MemOpndSlot = 0;
20559
20560   unsigned CurOp = 0;
20561
20562   DstReg = MI->getOperand(CurOp++).getReg();
20563   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20564   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20565   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20566   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20567
20568   MemOpndSlot = CurOp;
20569
20570   MVT PVT = getPointerTy(MF->getDataLayout());
20571   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20572          "Invalid Pointer Size!");
20573
20574   // For v = setjmp(buf), we generate
20575   //
20576   // thisMBB:
20577   //  buf[LabelOffset] = restoreMBB
20578   //  SjLjSetup restoreMBB
20579   //
20580   // mainMBB:
20581   //  v_main = 0
20582   //
20583   // sinkMBB:
20584   //  v = phi(main, restore)
20585   //
20586   // restoreMBB:
20587   //  if base pointer being used, load it from frame
20588   //  v_restore = 1
20589
20590   MachineBasicBlock *thisMBB = MBB;
20591   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20592   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20593   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20594   MF->insert(I, mainMBB);
20595   MF->insert(I, sinkMBB);
20596   MF->push_back(restoreMBB);
20597
20598   MachineInstrBuilder MIB;
20599
20600   // Transfer the remainder of BB and its successor edges to sinkMBB.
20601   sinkMBB->splice(sinkMBB->begin(), MBB,
20602                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20603   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20604
20605   // thisMBB:
20606   unsigned PtrStoreOpc = 0;
20607   unsigned LabelReg = 0;
20608   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20609   Reloc::Model RM = MF->getTarget().getRelocationModel();
20610   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20611                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20612
20613   // Prepare IP either in reg or imm.
20614   if (!UseImmLabel) {
20615     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20616     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20617     LabelReg = MRI.createVirtualRegister(PtrRC);
20618     if (Subtarget->is64Bit()) {
20619       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20620               .addReg(X86::RIP)
20621               .addImm(0)
20622               .addReg(0)
20623               .addMBB(restoreMBB)
20624               .addReg(0);
20625     } else {
20626       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20627       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20628               .addReg(XII->getGlobalBaseReg(MF))
20629               .addImm(0)
20630               .addReg(0)
20631               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20632               .addReg(0);
20633     }
20634   } else
20635     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20636   // Store IP
20637   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20638   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20639     if (i == X86::AddrDisp)
20640       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20641     else
20642       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20643   }
20644   if (!UseImmLabel)
20645     MIB.addReg(LabelReg);
20646   else
20647     MIB.addMBB(restoreMBB);
20648   MIB.setMemRefs(MMOBegin, MMOEnd);
20649   // Setup
20650   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20651           .addMBB(restoreMBB);
20652
20653   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20654   MIB.addRegMask(RegInfo->getNoPreservedMask());
20655   thisMBB->addSuccessor(mainMBB);
20656   thisMBB->addSuccessor(restoreMBB);
20657
20658   // mainMBB:
20659   //  EAX = 0
20660   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20661   mainMBB->addSuccessor(sinkMBB);
20662
20663   // sinkMBB:
20664   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20665           TII->get(X86::PHI), DstReg)
20666     .addReg(mainDstReg).addMBB(mainMBB)
20667     .addReg(restoreDstReg).addMBB(restoreMBB);
20668
20669   // restoreMBB:
20670   if (RegInfo->hasBasePointer(*MF)) {
20671     const bool Uses64BitFramePtr =
20672         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20673     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20674     X86FI->setRestoreBasePointer(MF);
20675     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20676     unsigned BasePtr = RegInfo->getBaseRegister();
20677     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20678     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20679                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20680       .setMIFlag(MachineInstr::FrameSetup);
20681   }
20682   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20683   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20684   restoreMBB->addSuccessor(sinkMBB);
20685
20686   MI->eraseFromParent();
20687   return sinkMBB;
20688 }
20689
20690 MachineBasicBlock *
20691 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20692                                      MachineBasicBlock *MBB) const {
20693   DebugLoc DL = MI->getDebugLoc();
20694   MachineFunction *MF = MBB->getParent();
20695   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20696   MachineRegisterInfo &MRI = MF->getRegInfo();
20697
20698   // Memory Reference
20699   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20700   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20701
20702   MVT PVT = getPointerTy(MF->getDataLayout());
20703   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20704          "Invalid Pointer Size!");
20705
20706   const TargetRegisterClass *RC =
20707     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20708   unsigned Tmp = MRI.createVirtualRegister(RC);
20709   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20710   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20711   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20712   unsigned SP = RegInfo->getStackRegister();
20713
20714   MachineInstrBuilder MIB;
20715
20716   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20717   const int64_t SPOffset = 2 * PVT.getStoreSize();
20718
20719   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20720   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20721
20722   // Reload FP
20723   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20724   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20725     MIB.addOperand(MI->getOperand(i));
20726   MIB.setMemRefs(MMOBegin, MMOEnd);
20727   // Reload IP
20728   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20729   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20730     if (i == X86::AddrDisp)
20731       MIB.addDisp(MI->getOperand(i), LabelOffset);
20732     else
20733       MIB.addOperand(MI->getOperand(i));
20734   }
20735   MIB.setMemRefs(MMOBegin, MMOEnd);
20736   // Reload SP
20737   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20738   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20739     if (i == X86::AddrDisp)
20740       MIB.addDisp(MI->getOperand(i), SPOffset);
20741     else
20742       MIB.addOperand(MI->getOperand(i));
20743   }
20744   MIB.setMemRefs(MMOBegin, MMOEnd);
20745   // Jump
20746   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20747
20748   MI->eraseFromParent();
20749   return MBB;
20750 }
20751
20752 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20753 // accumulator loops. Writing back to the accumulator allows the coalescer
20754 // to remove extra copies in the loop.
20755 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20756 MachineBasicBlock *
20757 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20758                                  MachineBasicBlock *MBB) const {
20759   MachineOperand &AddendOp = MI->getOperand(3);
20760
20761   // Bail out early if the addend isn't a register - we can't switch these.
20762   if (!AddendOp.isReg())
20763     return MBB;
20764
20765   MachineFunction &MF = *MBB->getParent();
20766   MachineRegisterInfo &MRI = MF.getRegInfo();
20767
20768   // Check whether the addend is defined by a PHI:
20769   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20770   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20771   if (!AddendDef.isPHI())
20772     return MBB;
20773
20774   // Look for the following pattern:
20775   // loop:
20776   //   %addend = phi [%entry, 0], [%loop, %result]
20777   //   ...
20778   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20779
20780   // Replace with:
20781   //   loop:
20782   //   %addend = phi [%entry, 0], [%loop, %result]
20783   //   ...
20784   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20785
20786   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20787     assert(AddendDef.getOperand(i).isReg());
20788     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20789     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20790     if (&PHISrcInst == MI) {
20791       // Found a matching instruction.
20792       unsigned NewFMAOpc = 0;
20793       switch (MI->getOpcode()) {
20794         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20795         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20796         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20797         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20798         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20799         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20800         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20801         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20802         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20803         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20804         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20805         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20806         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20807         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20808         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20809         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20810         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20811         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20812         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20813         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20814
20815         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20816         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20817         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20818         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20819         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20820         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20821         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20822         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20823         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20824         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20825         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20826         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20827         default: llvm_unreachable("Unrecognized FMA variant.");
20828       }
20829
20830       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20831       MachineInstrBuilder MIB =
20832         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20833         .addOperand(MI->getOperand(0))
20834         .addOperand(MI->getOperand(3))
20835         .addOperand(MI->getOperand(2))
20836         .addOperand(MI->getOperand(1));
20837       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20838       MI->eraseFromParent();
20839     }
20840   }
20841
20842   return MBB;
20843 }
20844
20845 MachineBasicBlock *
20846 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20847                                                MachineBasicBlock *BB) const {
20848   switch (MI->getOpcode()) {
20849   default: llvm_unreachable("Unexpected instr type to insert");
20850   case X86::TAILJMPd64:
20851   case X86::TAILJMPr64:
20852   case X86::TAILJMPm64:
20853   case X86::TAILJMPd64_REX:
20854   case X86::TAILJMPr64_REX:
20855   case X86::TAILJMPm64_REX:
20856     llvm_unreachable("TAILJMP64 would not be touched here.");
20857   case X86::TCRETURNdi64:
20858   case X86::TCRETURNri64:
20859   case X86::TCRETURNmi64:
20860     return BB;
20861   case X86::WIN_ALLOCA:
20862     return EmitLoweredWinAlloca(MI, BB);
20863   case X86::SEG_ALLOCA_32:
20864   case X86::SEG_ALLOCA_64:
20865     return EmitLoweredSegAlloca(MI, BB);
20866   case X86::TLSCall_32:
20867   case X86::TLSCall_64:
20868     return EmitLoweredTLSCall(MI, BB);
20869   case X86::CMOV_FR32:
20870   case X86::CMOV_FR64:
20871   case X86::CMOV_GR8:
20872   case X86::CMOV_GR16:
20873   case X86::CMOV_GR32:
20874   case X86::CMOV_RFP32:
20875   case X86::CMOV_RFP64:
20876   case X86::CMOV_RFP80:
20877   case X86::CMOV_V2F64:
20878   case X86::CMOV_V2I64:
20879   case X86::CMOV_V4F32:
20880   case X86::CMOV_V4F64:
20881   case X86::CMOV_V4I64:
20882   case X86::CMOV_V16F32:
20883   case X86::CMOV_V8F32:
20884   case X86::CMOV_V8F64:
20885   case X86::CMOV_V8I64:
20886   case X86::CMOV_V8I1:
20887   case X86::CMOV_V16I1:
20888   case X86::CMOV_V32I1:
20889   case X86::CMOV_V64I1:
20890     return EmitLoweredSelect(MI, BB);
20891
20892   case X86::RELEASE_FADD32mr:
20893   case X86::RELEASE_FADD64mr:
20894     return EmitLoweredAtomicFP(MI, BB);
20895
20896   case X86::FP32_TO_INT16_IN_MEM:
20897   case X86::FP32_TO_INT32_IN_MEM:
20898   case X86::FP32_TO_INT64_IN_MEM:
20899   case X86::FP64_TO_INT16_IN_MEM:
20900   case X86::FP64_TO_INT32_IN_MEM:
20901   case X86::FP64_TO_INT64_IN_MEM:
20902   case X86::FP80_TO_INT16_IN_MEM:
20903   case X86::FP80_TO_INT32_IN_MEM:
20904   case X86::FP80_TO_INT64_IN_MEM: {
20905     MachineFunction *F = BB->getParent();
20906     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20907     DebugLoc DL = MI->getDebugLoc();
20908
20909     // Change the floating point control register to use "round towards zero"
20910     // mode when truncating to an integer value.
20911     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20912     addFrameReference(BuildMI(*BB, MI, DL,
20913                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20914
20915     // Load the old value of the high byte of the control word...
20916     unsigned OldCW =
20917       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20918     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20919                       CWFrameIdx);
20920
20921     // Set the high part to be round to zero...
20922     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20923       .addImm(0xC7F);
20924
20925     // Reload the modified control word now...
20926     addFrameReference(BuildMI(*BB, MI, DL,
20927                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20928
20929     // Restore the memory image of control word to original value
20930     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20931       .addReg(OldCW);
20932
20933     // Get the X86 opcode to use.
20934     unsigned Opc;
20935     switch (MI->getOpcode()) {
20936     default: llvm_unreachable("illegal opcode!");
20937     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20938     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20939     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20940     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20941     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20942     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20943     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20944     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20945     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20946     }
20947
20948     X86AddressMode AM;
20949     MachineOperand &Op = MI->getOperand(0);
20950     if (Op.isReg()) {
20951       AM.BaseType = X86AddressMode::RegBase;
20952       AM.Base.Reg = Op.getReg();
20953     } else {
20954       AM.BaseType = X86AddressMode::FrameIndexBase;
20955       AM.Base.FrameIndex = Op.getIndex();
20956     }
20957     Op = MI->getOperand(1);
20958     if (Op.isImm())
20959       AM.Scale = Op.getImm();
20960     Op = MI->getOperand(2);
20961     if (Op.isImm())
20962       AM.IndexReg = Op.getImm();
20963     Op = MI->getOperand(3);
20964     if (Op.isGlobal()) {
20965       AM.GV = Op.getGlobal();
20966     } else {
20967       AM.Disp = Op.getImm();
20968     }
20969     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20970                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20971
20972     // Reload the original control word now.
20973     addFrameReference(BuildMI(*BB, MI, DL,
20974                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20975
20976     MI->eraseFromParent();   // The pseudo instruction is gone now.
20977     return BB;
20978   }
20979     // String/text processing lowering.
20980   case X86::PCMPISTRM128REG:
20981   case X86::VPCMPISTRM128REG:
20982   case X86::PCMPISTRM128MEM:
20983   case X86::VPCMPISTRM128MEM:
20984   case X86::PCMPESTRM128REG:
20985   case X86::VPCMPESTRM128REG:
20986   case X86::PCMPESTRM128MEM:
20987   case X86::VPCMPESTRM128MEM:
20988     assert(Subtarget->hasSSE42() &&
20989            "Target must have SSE4.2 or AVX features enabled");
20990     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20991
20992   // String/text processing lowering.
20993   case X86::PCMPISTRIREG:
20994   case X86::VPCMPISTRIREG:
20995   case X86::PCMPISTRIMEM:
20996   case X86::VPCMPISTRIMEM:
20997   case X86::PCMPESTRIREG:
20998   case X86::VPCMPESTRIREG:
20999   case X86::PCMPESTRIMEM:
21000   case X86::VPCMPESTRIMEM:
21001     assert(Subtarget->hasSSE42() &&
21002            "Target must have SSE4.2 or AVX features enabled");
21003     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21004
21005   // Thread synchronization.
21006   case X86::MONITOR:
21007     return EmitMonitor(MI, BB, Subtarget);
21008
21009   // xbegin
21010   case X86::XBEGIN:
21011     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21012
21013   case X86::VASTART_SAVE_XMM_REGS:
21014     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21015
21016   case X86::VAARG_64:
21017     return EmitVAARG64WithCustomInserter(MI, BB);
21018
21019   case X86::EH_SjLj_SetJmp32:
21020   case X86::EH_SjLj_SetJmp64:
21021     return emitEHSjLjSetJmp(MI, BB);
21022
21023   case X86::EH_SjLj_LongJmp32:
21024   case X86::EH_SjLj_LongJmp64:
21025     return emitEHSjLjLongJmp(MI, BB);
21026
21027   case TargetOpcode::STATEPOINT:
21028     // As an implementation detail, STATEPOINT shares the STACKMAP format at
21029     // this point in the process.  We diverge later.
21030     return emitPatchPoint(MI, BB);
21031
21032   case TargetOpcode::STACKMAP:
21033   case TargetOpcode::PATCHPOINT:
21034     return emitPatchPoint(MI, BB);
21035
21036   case X86::VFMADDPDr213r:
21037   case X86::VFMADDPSr213r:
21038   case X86::VFMADDSDr213r:
21039   case X86::VFMADDSSr213r:
21040   case X86::VFMSUBPDr213r:
21041   case X86::VFMSUBPSr213r:
21042   case X86::VFMSUBSDr213r:
21043   case X86::VFMSUBSSr213r:
21044   case X86::VFNMADDPDr213r:
21045   case X86::VFNMADDPSr213r:
21046   case X86::VFNMADDSDr213r:
21047   case X86::VFNMADDSSr213r:
21048   case X86::VFNMSUBPDr213r:
21049   case X86::VFNMSUBPSr213r:
21050   case X86::VFNMSUBSDr213r:
21051   case X86::VFNMSUBSSr213r:
21052   case X86::VFMADDSUBPDr213r:
21053   case X86::VFMADDSUBPSr213r:
21054   case X86::VFMSUBADDPDr213r:
21055   case X86::VFMSUBADDPSr213r:
21056   case X86::VFMADDPDr213rY:
21057   case X86::VFMADDPSr213rY:
21058   case X86::VFMSUBPDr213rY:
21059   case X86::VFMSUBPSr213rY:
21060   case X86::VFNMADDPDr213rY:
21061   case X86::VFNMADDPSr213rY:
21062   case X86::VFNMSUBPDr213rY:
21063   case X86::VFNMSUBPSr213rY:
21064   case X86::VFMADDSUBPDr213rY:
21065   case X86::VFMADDSUBPSr213rY:
21066   case X86::VFMSUBADDPDr213rY:
21067   case X86::VFMSUBADDPSr213rY:
21068     return emitFMA3Instr(MI, BB);
21069   }
21070 }
21071
21072 //===----------------------------------------------------------------------===//
21073 //                           X86 Optimization Hooks
21074 //===----------------------------------------------------------------------===//
21075
21076 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21077                                                       APInt &KnownZero,
21078                                                       APInt &KnownOne,
21079                                                       const SelectionDAG &DAG,
21080                                                       unsigned Depth) const {
21081   unsigned BitWidth = KnownZero.getBitWidth();
21082   unsigned Opc = Op.getOpcode();
21083   assert((Opc >= ISD::BUILTIN_OP_END ||
21084           Opc == ISD::INTRINSIC_WO_CHAIN ||
21085           Opc == ISD::INTRINSIC_W_CHAIN ||
21086           Opc == ISD::INTRINSIC_VOID) &&
21087          "Should use MaskedValueIsZero if you don't know whether Op"
21088          " is a target node!");
21089
21090   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21091   switch (Opc) {
21092   default: break;
21093   case X86ISD::ADD:
21094   case X86ISD::SUB:
21095   case X86ISD::ADC:
21096   case X86ISD::SBB:
21097   case X86ISD::SMUL:
21098   case X86ISD::UMUL:
21099   case X86ISD::INC:
21100   case X86ISD::DEC:
21101   case X86ISD::OR:
21102   case X86ISD::XOR:
21103   case X86ISD::AND:
21104     // These nodes' second result is a boolean.
21105     if (Op.getResNo() == 0)
21106       break;
21107     // Fallthrough
21108   case X86ISD::SETCC:
21109     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21110     break;
21111   case ISD::INTRINSIC_WO_CHAIN: {
21112     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21113     unsigned NumLoBits = 0;
21114     switch (IntId) {
21115     default: break;
21116     case Intrinsic::x86_sse_movmsk_ps:
21117     case Intrinsic::x86_avx_movmsk_ps_256:
21118     case Intrinsic::x86_sse2_movmsk_pd:
21119     case Intrinsic::x86_avx_movmsk_pd_256:
21120     case Intrinsic::x86_mmx_pmovmskb:
21121     case Intrinsic::x86_sse2_pmovmskb_128:
21122     case Intrinsic::x86_avx2_pmovmskb: {
21123       // High bits of movmskp{s|d}, pmovmskb are known zero.
21124       switch (IntId) {
21125         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21126         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21127         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21128         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21129         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21130         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21131         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21132         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21133       }
21134       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21135       break;
21136     }
21137     }
21138     break;
21139   }
21140   }
21141 }
21142
21143 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21144   SDValue Op,
21145   const SelectionDAG &,
21146   unsigned Depth) const {
21147   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21148   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21149     return Op.getValueType().getScalarType().getSizeInBits();
21150
21151   // Fallback case.
21152   return 1;
21153 }
21154
21155 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21156 /// node is a GlobalAddress + offset.
21157 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21158                                        const GlobalValue* &GA,
21159                                        int64_t &Offset) const {
21160   if (N->getOpcode() == X86ISD::Wrapper) {
21161     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21162       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21163       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21164       return true;
21165     }
21166   }
21167   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21168 }
21169
21170 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21171 /// same as extracting the high 128-bit part of 256-bit vector and then
21172 /// inserting the result into the low part of a new 256-bit vector
21173 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21174   EVT VT = SVOp->getValueType(0);
21175   unsigned NumElems = VT.getVectorNumElements();
21176
21177   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21178   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21179     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21180         SVOp->getMaskElt(j) >= 0)
21181       return false;
21182
21183   return true;
21184 }
21185
21186 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21187 /// same as extracting the low 128-bit part of 256-bit vector and then
21188 /// inserting the result into the high part of a new 256-bit vector
21189 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21190   EVT VT = SVOp->getValueType(0);
21191   unsigned NumElems = VT.getVectorNumElements();
21192
21193   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21194   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21195     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21196         SVOp->getMaskElt(j) >= 0)
21197       return false;
21198
21199   return true;
21200 }
21201
21202 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21203 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21204                                         TargetLowering::DAGCombinerInfo &DCI,
21205                                         const X86Subtarget* Subtarget) {
21206   SDLoc dl(N);
21207   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21208   SDValue V1 = SVOp->getOperand(0);
21209   SDValue V2 = SVOp->getOperand(1);
21210   EVT VT = SVOp->getValueType(0);
21211   unsigned NumElems = VT.getVectorNumElements();
21212
21213   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21214       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21215     //
21216     //                   0,0,0,...
21217     //                      |
21218     //    V      UNDEF    BUILD_VECTOR    UNDEF
21219     //     \      /           \           /
21220     //  CONCAT_VECTOR         CONCAT_VECTOR
21221     //         \                  /
21222     //          \                /
21223     //          RESULT: V + zero extended
21224     //
21225     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21226         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21227         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21228       return SDValue();
21229
21230     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21231       return SDValue();
21232
21233     // To match the shuffle mask, the first half of the mask should
21234     // be exactly the first vector, and all the rest a splat with the
21235     // first element of the second one.
21236     for (unsigned i = 0; i != NumElems/2; ++i)
21237       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21238           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21239         return SDValue();
21240
21241     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21242     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21243       if (Ld->hasNUsesOfValue(1, 0)) {
21244         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21245         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21246         SDValue ResNode =
21247           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21248                                   Ld->getMemoryVT(),
21249                                   Ld->getPointerInfo(),
21250                                   Ld->getAlignment(),
21251                                   false/*isVolatile*/, true/*ReadMem*/,
21252                                   false/*WriteMem*/);
21253
21254         // Make sure the newly-created LOAD is in the same position as Ld in
21255         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21256         // and update uses of Ld's output chain to use the TokenFactor.
21257         if (Ld->hasAnyUseOfValue(1)) {
21258           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21259                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21260           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21261           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21262                                  SDValue(ResNode.getNode(), 1));
21263         }
21264
21265         return DAG.getBitcast(VT, ResNode);
21266       }
21267     }
21268
21269     // Emit a zeroed vector and insert the desired subvector on its
21270     // first half.
21271     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21272     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21273     return DCI.CombineTo(N, InsV);
21274   }
21275
21276   //===--------------------------------------------------------------------===//
21277   // Combine some shuffles into subvector extracts and inserts:
21278   //
21279
21280   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21281   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21282     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21283     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21284     return DCI.CombineTo(N, InsV);
21285   }
21286
21287   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21288   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21289     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21290     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21291     return DCI.CombineTo(N, InsV);
21292   }
21293
21294   return SDValue();
21295 }
21296
21297 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21298 /// possible.
21299 ///
21300 /// This is the leaf of the recursive combinine below. When we have found some
21301 /// chain of single-use x86 shuffle instructions and accumulated the combined
21302 /// shuffle mask represented by them, this will try to pattern match that mask
21303 /// into either a single instruction if there is a special purpose instruction
21304 /// for this operation, or into a PSHUFB instruction which is a fully general
21305 /// instruction but should only be used to replace chains over a certain depth.
21306 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21307                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21308                                    TargetLowering::DAGCombinerInfo &DCI,
21309                                    const X86Subtarget *Subtarget) {
21310   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21311
21312   // Find the operand that enters the chain. Note that multiple uses are OK
21313   // here, we're not going to remove the operand we find.
21314   SDValue Input = Op.getOperand(0);
21315   while (Input.getOpcode() == ISD::BITCAST)
21316     Input = Input.getOperand(0);
21317
21318   MVT VT = Input.getSimpleValueType();
21319   MVT RootVT = Root.getSimpleValueType();
21320   SDLoc DL(Root);
21321
21322   // Just remove no-op shuffle masks.
21323   if (Mask.size() == 1) {
21324     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21325                   /*AddTo*/ true);
21326     return true;
21327   }
21328
21329   // Use the float domain if the operand type is a floating point type.
21330   bool FloatDomain = VT.isFloatingPoint();
21331
21332   // For floating point shuffles, we don't have free copies in the shuffle
21333   // instructions or the ability to load as part of the instruction, so
21334   // canonicalize their shuffles to UNPCK or MOV variants.
21335   //
21336   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21337   // vectors because it can have a load folded into it that UNPCK cannot. This
21338   // doesn't preclude something switching to the shorter encoding post-RA.
21339   //
21340   // FIXME: Should teach these routines about AVX vector widths.
21341   if (FloatDomain && VT.getSizeInBits() == 128) {
21342     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21343       bool Lo = Mask.equals({0, 0});
21344       unsigned Shuffle;
21345       MVT ShuffleVT;
21346       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21347       // is no slower than UNPCKLPD but has the option to fold the input operand
21348       // into even an unaligned memory load.
21349       if (Lo && Subtarget->hasSSE3()) {
21350         Shuffle = X86ISD::MOVDDUP;
21351         ShuffleVT = MVT::v2f64;
21352       } else {
21353         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21354         // than the UNPCK variants.
21355         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21356         ShuffleVT = MVT::v4f32;
21357       }
21358       if (Depth == 1 && Root->getOpcode() == Shuffle)
21359         return false; // Nothing to do!
21360       Op = DAG.getBitcast(ShuffleVT, Input);
21361       DCI.AddToWorklist(Op.getNode());
21362       if (Shuffle == X86ISD::MOVDDUP)
21363         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21364       else
21365         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21366       DCI.AddToWorklist(Op.getNode());
21367       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21368                     /*AddTo*/ true);
21369       return true;
21370     }
21371     if (Subtarget->hasSSE3() &&
21372         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21373       bool Lo = Mask.equals({0, 0, 2, 2});
21374       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21375       MVT ShuffleVT = MVT::v4f32;
21376       if (Depth == 1 && Root->getOpcode() == Shuffle)
21377         return false; // Nothing to do!
21378       Op = DAG.getBitcast(ShuffleVT, Input);
21379       DCI.AddToWorklist(Op.getNode());
21380       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21381       DCI.AddToWorklist(Op.getNode());
21382       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21383                     /*AddTo*/ true);
21384       return true;
21385     }
21386     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21387       bool Lo = Mask.equals({0, 0, 1, 1});
21388       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21389       MVT ShuffleVT = MVT::v4f32;
21390       if (Depth == 1 && Root->getOpcode() == Shuffle)
21391         return false; // Nothing to do!
21392       Op = DAG.getBitcast(ShuffleVT, Input);
21393       DCI.AddToWorklist(Op.getNode());
21394       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21395       DCI.AddToWorklist(Op.getNode());
21396       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21397                     /*AddTo*/ true);
21398       return true;
21399     }
21400   }
21401
21402   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21403   // variants as none of these have single-instruction variants that are
21404   // superior to the UNPCK formulation.
21405   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21406       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21407        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21408        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21409        Mask.equals(
21410            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21411     bool Lo = Mask[0] == 0;
21412     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21413     if (Depth == 1 && Root->getOpcode() == Shuffle)
21414       return false; // Nothing to do!
21415     MVT ShuffleVT;
21416     switch (Mask.size()) {
21417     case 8:
21418       ShuffleVT = MVT::v8i16;
21419       break;
21420     case 16:
21421       ShuffleVT = MVT::v16i8;
21422       break;
21423     default:
21424       llvm_unreachable("Impossible mask size!");
21425     };
21426     Op = DAG.getBitcast(ShuffleVT, Input);
21427     DCI.AddToWorklist(Op.getNode());
21428     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21429     DCI.AddToWorklist(Op.getNode());
21430     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21431                   /*AddTo*/ true);
21432     return true;
21433   }
21434
21435   // Don't try to re-form single instruction chains under any circumstances now
21436   // that we've done encoding canonicalization for them.
21437   if (Depth < 2)
21438     return false;
21439
21440   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21441   // can replace them with a single PSHUFB instruction profitably. Intel's
21442   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21443   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21444   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21445     SmallVector<SDValue, 16> PSHUFBMask;
21446     int NumBytes = VT.getSizeInBits() / 8;
21447     int Ratio = NumBytes / Mask.size();
21448     for (int i = 0; i < NumBytes; ++i) {
21449       if (Mask[i / Ratio] == SM_SentinelUndef) {
21450         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21451         continue;
21452       }
21453       int M = Mask[i / Ratio] != SM_SentinelZero
21454                   ? Ratio * Mask[i / Ratio] + i % Ratio
21455                   : 255;
21456       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21457     }
21458     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21459     Op = DAG.getBitcast(ByteVT, Input);
21460     DCI.AddToWorklist(Op.getNode());
21461     SDValue PSHUFBMaskOp =
21462         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21463     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21464     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21465     DCI.AddToWorklist(Op.getNode());
21466     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21467                   /*AddTo*/ true);
21468     return true;
21469   }
21470
21471   // Failed to find any combines.
21472   return false;
21473 }
21474
21475 /// \brief Fully generic combining of x86 shuffle instructions.
21476 ///
21477 /// This should be the last combine run over the x86 shuffle instructions. Once
21478 /// they have been fully optimized, this will recursively consider all chains
21479 /// of single-use shuffle instructions, build a generic model of the cumulative
21480 /// shuffle operation, and check for simpler instructions which implement this
21481 /// operation. We use this primarily for two purposes:
21482 ///
21483 /// 1) Collapse generic shuffles to specialized single instructions when
21484 ///    equivalent. In most cases, this is just an encoding size win, but
21485 ///    sometimes we will collapse multiple generic shuffles into a single
21486 ///    special-purpose shuffle.
21487 /// 2) Look for sequences of shuffle instructions with 3 or more total
21488 ///    instructions, and replace them with the slightly more expensive SSSE3
21489 ///    PSHUFB instruction if available. We do this as the last combining step
21490 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21491 ///    a suitable short sequence of other instructions. The PHUFB will either
21492 ///    use a register or have to read from memory and so is slightly (but only
21493 ///    slightly) more expensive than the other shuffle instructions.
21494 ///
21495 /// Because this is inherently a quadratic operation (for each shuffle in
21496 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21497 /// This should never be an issue in practice as the shuffle lowering doesn't
21498 /// produce sequences of more than 8 instructions.
21499 ///
21500 /// FIXME: We will currently miss some cases where the redundant shuffling
21501 /// would simplify under the threshold for PSHUFB formation because of
21502 /// combine-ordering. To fix this, we should do the redundant instruction
21503 /// combining in this recursive walk.
21504 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21505                                           ArrayRef<int> RootMask,
21506                                           int Depth, bool HasPSHUFB,
21507                                           SelectionDAG &DAG,
21508                                           TargetLowering::DAGCombinerInfo &DCI,
21509                                           const X86Subtarget *Subtarget) {
21510   // Bound the depth of our recursive combine because this is ultimately
21511   // quadratic in nature.
21512   if (Depth > 8)
21513     return false;
21514
21515   // Directly rip through bitcasts to find the underlying operand.
21516   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21517     Op = Op.getOperand(0);
21518
21519   MVT VT = Op.getSimpleValueType();
21520   if (!VT.isVector())
21521     return false; // Bail if we hit a non-vector.
21522
21523   assert(Root.getSimpleValueType().isVector() &&
21524          "Shuffles operate on vector types!");
21525   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21526          "Can only combine shuffles of the same vector register size.");
21527
21528   if (!isTargetShuffle(Op.getOpcode()))
21529     return false;
21530   SmallVector<int, 16> OpMask;
21531   bool IsUnary;
21532   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21533   // We only can combine unary shuffles which we can decode the mask for.
21534   if (!HaveMask || !IsUnary)
21535     return false;
21536
21537   assert(VT.getVectorNumElements() == OpMask.size() &&
21538          "Different mask size from vector size!");
21539   assert(((RootMask.size() > OpMask.size() &&
21540            RootMask.size() % OpMask.size() == 0) ||
21541           (OpMask.size() > RootMask.size() &&
21542            OpMask.size() % RootMask.size() == 0) ||
21543           OpMask.size() == RootMask.size()) &&
21544          "The smaller number of elements must divide the larger.");
21545   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21546   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21547   assert(((RootRatio == 1 && OpRatio == 1) ||
21548           (RootRatio == 1) != (OpRatio == 1)) &&
21549          "Must not have a ratio for both incoming and op masks!");
21550
21551   SmallVector<int, 16> Mask;
21552   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21553
21554   // Merge this shuffle operation's mask into our accumulated mask. Note that
21555   // this shuffle's mask will be the first applied to the input, followed by the
21556   // root mask to get us all the way to the root value arrangement. The reason
21557   // for this order is that we are recursing up the operation chain.
21558   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21559     int RootIdx = i / RootRatio;
21560     if (RootMask[RootIdx] < 0) {
21561       // This is a zero or undef lane, we're done.
21562       Mask.push_back(RootMask[RootIdx]);
21563       continue;
21564     }
21565
21566     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21567     int OpIdx = RootMaskedIdx / OpRatio;
21568     if (OpMask[OpIdx] < 0) {
21569       // The incoming lanes are zero or undef, it doesn't matter which ones we
21570       // are using.
21571       Mask.push_back(OpMask[OpIdx]);
21572       continue;
21573     }
21574
21575     // Ok, we have non-zero lanes, map them through.
21576     Mask.push_back(OpMask[OpIdx] * OpRatio +
21577                    RootMaskedIdx % OpRatio);
21578   }
21579
21580   // See if we can recurse into the operand to combine more things.
21581   switch (Op.getOpcode()) {
21582     case X86ISD::PSHUFB:
21583       HasPSHUFB = true;
21584     case X86ISD::PSHUFD:
21585     case X86ISD::PSHUFHW:
21586     case X86ISD::PSHUFLW:
21587       if (Op.getOperand(0).hasOneUse() &&
21588           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21589                                         HasPSHUFB, DAG, DCI, Subtarget))
21590         return true;
21591       break;
21592
21593     case X86ISD::UNPCKL:
21594     case X86ISD::UNPCKH:
21595       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21596       // We can't check for single use, we have to check that this shuffle is the only user.
21597       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21598           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21599                                         HasPSHUFB, DAG, DCI, Subtarget))
21600           return true;
21601       break;
21602   }
21603
21604   // Minor canonicalization of the accumulated shuffle mask to make it easier
21605   // to match below. All this does is detect masks with squential pairs of
21606   // elements, and shrink them to the half-width mask. It does this in a loop
21607   // so it will reduce the size of the mask to the minimal width mask which
21608   // performs an equivalent shuffle.
21609   SmallVector<int, 16> WidenedMask;
21610   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21611     Mask = std::move(WidenedMask);
21612     WidenedMask.clear();
21613   }
21614
21615   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21616                                 Subtarget);
21617 }
21618
21619 /// \brief Get the PSHUF-style mask from PSHUF node.
21620 ///
21621 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21622 /// PSHUF-style masks that can be reused with such instructions.
21623 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21624   MVT VT = N.getSimpleValueType();
21625   SmallVector<int, 4> Mask;
21626   bool IsUnary;
21627   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21628   (void)HaveMask;
21629   assert(HaveMask);
21630
21631   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21632   // matter. Check that the upper masks are repeats and remove them.
21633   if (VT.getSizeInBits() > 128) {
21634     int LaneElts = 128 / VT.getScalarSizeInBits();
21635 #ifndef NDEBUG
21636     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21637       for (int j = 0; j < LaneElts; ++j)
21638         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21639                "Mask doesn't repeat in high 128-bit lanes!");
21640 #endif
21641     Mask.resize(LaneElts);
21642   }
21643
21644   switch (N.getOpcode()) {
21645   case X86ISD::PSHUFD:
21646     return Mask;
21647   case X86ISD::PSHUFLW:
21648     Mask.resize(4);
21649     return Mask;
21650   case X86ISD::PSHUFHW:
21651     Mask.erase(Mask.begin(), Mask.begin() + 4);
21652     for (int &M : Mask)
21653       M -= 4;
21654     return Mask;
21655   default:
21656     llvm_unreachable("No valid shuffle instruction found!");
21657   }
21658 }
21659
21660 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21661 ///
21662 /// We walk up the chain and look for a combinable shuffle, skipping over
21663 /// shuffles that we could hoist this shuffle's transformation past without
21664 /// altering anything.
21665 static SDValue
21666 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21667                              SelectionDAG &DAG,
21668                              TargetLowering::DAGCombinerInfo &DCI) {
21669   assert(N.getOpcode() == X86ISD::PSHUFD &&
21670          "Called with something other than an x86 128-bit half shuffle!");
21671   SDLoc DL(N);
21672
21673   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21674   // of the shuffles in the chain so that we can form a fresh chain to replace
21675   // this one.
21676   SmallVector<SDValue, 8> Chain;
21677   SDValue V = N.getOperand(0);
21678   for (; V.hasOneUse(); V = V.getOperand(0)) {
21679     switch (V.getOpcode()) {
21680     default:
21681       return SDValue(); // Nothing combined!
21682
21683     case ISD::BITCAST:
21684       // Skip bitcasts as we always know the type for the target specific
21685       // instructions.
21686       continue;
21687
21688     case X86ISD::PSHUFD:
21689       // Found another dword shuffle.
21690       break;
21691
21692     case X86ISD::PSHUFLW:
21693       // Check that the low words (being shuffled) are the identity in the
21694       // dword shuffle, and the high words are self-contained.
21695       if (Mask[0] != 0 || Mask[1] != 1 ||
21696           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21697         return SDValue();
21698
21699       Chain.push_back(V);
21700       continue;
21701
21702     case X86ISD::PSHUFHW:
21703       // Check that the high words (being shuffled) are the identity in the
21704       // dword shuffle, and the low words are self-contained.
21705       if (Mask[2] != 2 || Mask[3] != 3 ||
21706           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21707         return SDValue();
21708
21709       Chain.push_back(V);
21710       continue;
21711
21712     case X86ISD::UNPCKL:
21713     case X86ISD::UNPCKH:
21714       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21715       // shuffle into a preceding word shuffle.
21716       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21717           V.getSimpleValueType().getScalarType() != MVT::i16)
21718         return SDValue();
21719
21720       // Search for a half-shuffle which we can combine with.
21721       unsigned CombineOp =
21722           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21723       if (V.getOperand(0) != V.getOperand(1) ||
21724           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21725         return SDValue();
21726       Chain.push_back(V);
21727       V = V.getOperand(0);
21728       do {
21729         switch (V.getOpcode()) {
21730         default:
21731           return SDValue(); // Nothing to combine.
21732
21733         case X86ISD::PSHUFLW:
21734         case X86ISD::PSHUFHW:
21735           if (V.getOpcode() == CombineOp)
21736             break;
21737
21738           Chain.push_back(V);
21739
21740           // Fallthrough!
21741         case ISD::BITCAST:
21742           V = V.getOperand(0);
21743           continue;
21744         }
21745         break;
21746       } while (V.hasOneUse());
21747       break;
21748     }
21749     // Break out of the loop if we break out of the switch.
21750     break;
21751   }
21752
21753   if (!V.hasOneUse())
21754     // We fell out of the loop without finding a viable combining instruction.
21755     return SDValue();
21756
21757   // Merge this node's mask and our incoming mask.
21758   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21759   for (int &M : Mask)
21760     M = VMask[M];
21761   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21762                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21763
21764   // Rebuild the chain around this new shuffle.
21765   while (!Chain.empty()) {
21766     SDValue W = Chain.pop_back_val();
21767
21768     if (V.getValueType() != W.getOperand(0).getValueType())
21769       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21770
21771     switch (W.getOpcode()) {
21772     default:
21773       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21774
21775     case X86ISD::UNPCKL:
21776     case X86ISD::UNPCKH:
21777       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21778       break;
21779
21780     case X86ISD::PSHUFD:
21781     case X86ISD::PSHUFLW:
21782     case X86ISD::PSHUFHW:
21783       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21784       break;
21785     }
21786   }
21787   if (V.getValueType() != N.getValueType())
21788     V = DAG.getBitcast(N.getValueType(), V);
21789
21790   // Return the new chain to replace N.
21791   return V;
21792 }
21793
21794 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21795 ///
21796 /// We walk up the chain, skipping shuffles of the other half and looking
21797 /// through shuffles which switch halves trying to find a shuffle of the same
21798 /// pair of dwords.
21799 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21800                                         SelectionDAG &DAG,
21801                                         TargetLowering::DAGCombinerInfo &DCI) {
21802   assert(
21803       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21804       "Called with something other than an x86 128-bit half shuffle!");
21805   SDLoc DL(N);
21806   unsigned CombineOpcode = N.getOpcode();
21807
21808   // Walk up a single-use chain looking for a combinable shuffle.
21809   SDValue V = N.getOperand(0);
21810   for (; V.hasOneUse(); V = V.getOperand(0)) {
21811     switch (V.getOpcode()) {
21812     default:
21813       return false; // Nothing combined!
21814
21815     case ISD::BITCAST:
21816       // Skip bitcasts as we always know the type for the target specific
21817       // instructions.
21818       continue;
21819
21820     case X86ISD::PSHUFLW:
21821     case X86ISD::PSHUFHW:
21822       if (V.getOpcode() == CombineOpcode)
21823         break;
21824
21825       // Other-half shuffles are no-ops.
21826       continue;
21827     }
21828     // Break out of the loop if we break out of the switch.
21829     break;
21830   }
21831
21832   if (!V.hasOneUse())
21833     // We fell out of the loop without finding a viable combining instruction.
21834     return false;
21835
21836   // Combine away the bottom node as its shuffle will be accumulated into
21837   // a preceding shuffle.
21838   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21839
21840   // Record the old value.
21841   SDValue Old = V;
21842
21843   // Merge this node's mask and our incoming mask (adjusted to account for all
21844   // the pshufd instructions encountered).
21845   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21846   for (int &M : Mask)
21847     M = VMask[M];
21848   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21849                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21850
21851   // Check that the shuffles didn't cancel each other out. If not, we need to
21852   // combine to the new one.
21853   if (Old != V)
21854     // Replace the combinable shuffle with the combined one, updating all users
21855     // so that we re-evaluate the chain here.
21856     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21857
21858   return true;
21859 }
21860
21861 /// \brief Try to combine x86 target specific shuffles.
21862 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21863                                            TargetLowering::DAGCombinerInfo &DCI,
21864                                            const X86Subtarget *Subtarget) {
21865   SDLoc DL(N);
21866   MVT VT = N.getSimpleValueType();
21867   SmallVector<int, 4> Mask;
21868
21869   switch (N.getOpcode()) {
21870   case X86ISD::PSHUFD:
21871   case X86ISD::PSHUFLW:
21872   case X86ISD::PSHUFHW:
21873     Mask = getPSHUFShuffleMask(N);
21874     assert(Mask.size() == 4);
21875     break;
21876   default:
21877     return SDValue();
21878   }
21879
21880   // Nuke no-op shuffles that show up after combining.
21881   if (isNoopShuffleMask(Mask))
21882     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21883
21884   // Look for simplifications involving one or two shuffle instructions.
21885   SDValue V = N.getOperand(0);
21886   switch (N.getOpcode()) {
21887   default:
21888     break;
21889   case X86ISD::PSHUFLW:
21890   case X86ISD::PSHUFHW:
21891     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21892
21893     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21894       return SDValue(); // We combined away this shuffle, so we're done.
21895
21896     // See if this reduces to a PSHUFD which is no more expensive and can
21897     // combine with more operations. Note that it has to at least flip the
21898     // dwords as otherwise it would have been removed as a no-op.
21899     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21900       int DMask[] = {0, 1, 2, 3};
21901       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21902       DMask[DOffset + 0] = DOffset + 1;
21903       DMask[DOffset + 1] = DOffset + 0;
21904       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21905       V = DAG.getBitcast(DVT, V);
21906       DCI.AddToWorklist(V.getNode());
21907       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21908                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21909       DCI.AddToWorklist(V.getNode());
21910       return DAG.getBitcast(VT, V);
21911     }
21912
21913     // Look for shuffle patterns which can be implemented as a single unpack.
21914     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21915     // only works when we have a PSHUFD followed by two half-shuffles.
21916     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21917         (V.getOpcode() == X86ISD::PSHUFLW ||
21918          V.getOpcode() == X86ISD::PSHUFHW) &&
21919         V.getOpcode() != N.getOpcode() &&
21920         V.hasOneUse()) {
21921       SDValue D = V.getOperand(0);
21922       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21923         D = D.getOperand(0);
21924       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21925         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21926         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21927         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21928         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21929         int WordMask[8];
21930         for (int i = 0; i < 4; ++i) {
21931           WordMask[i + NOffset] = Mask[i] + NOffset;
21932           WordMask[i + VOffset] = VMask[i] + VOffset;
21933         }
21934         // Map the word mask through the DWord mask.
21935         int MappedMask[8];
21936         for (int i = 0; i < 8; ++i)
21937           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21938         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21939             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21940           // We can replace all three shuffles with an unpack.
21941           V = DAG.getBitcast(VT, D.getOperand(0));
21942           DCI.AddToWorklist(V.getNode());
21943           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21944                                                 : X86ISD::UNPCKH,
21945                              DL, VT, V, V);
21946         }
21947       }
21948     }
21949
21950     break;
21951
21952   case X86ISD::PSHUFD:
21953     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21954       return NewN;
21955
21956     break;
21957   }
21958
21959   return SDValue();
21960 }
21961
21962 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21963 ///
21964 /// We combine this directly on the abstract vector shuffle nodes so it is
21965 /// easier to generically match. We also insert dummy vector shuffle nodes for
21966 /// the operands which explicitly discard the lanes which are unused by this
21967 /// operation to try to flow through the rest of the combiner the fact that
21968 /// they're unused.
21969 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21970   SDLoc DL(N);
21971   EVT VT = N->getValueType(0);
21972
21973   // We only handle target-independent shuffles.
21974   // FIXME: It would be easy and harmless to use the target shuffle mask
21975   // extraction tool to support more.
21976   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21977     return SDValue();
21978
21979   auto *SVN = cast<ShuffleVectorSDNode>(N);
21980   ArrayRef<int> Mask = SVN->getMask();
21981   SDValue V1 = N->getOperand(0);
21982   SDValue V2 = N->getOperand(1);
21983
21984   // We require the first shuffle operand to be the SUB node, and the second to
21985   // be the ADD node.
21986   // FIXME: We should support the commuted patterns.
21987   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21988     return SDValue();
21989
21990   // If there are other uses of these operations we can't fold them.
21991   if (!V1->hasOneUse() || !V2->hasOneUse())
21992     return SDValue();
21993
21994   // Ensure that both operations have the same operands. Note that we can
21995   // commute the FADD operands.
21996   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21997   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21998       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21999     return SDValue();
22000
22001   // We're looking for blends between FADD and FSUB nodes. We insist on these
22002   // nodes being lined up in a specific expected pattern.
22003   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22004         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22005         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22006     return SDValue();
22007
22008   // Only specific types are legal at this point, assert so we notice if and
22009   // when these change.
22010   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22011           VT == MVT::v4f64) &&
22012          "Unknown vector type encountered!");
22013
22014   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22015 }
22016
22017 /// PerformShuffleCombine - Performs several different shuffle combines.
22018 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22019                                      TargetLowering::DAGCombinerInfo &DCI,
22020                                      const X86Subtarget *Subtarget) {
22021   SDLoc dl(N);
22022   SDValue N0 = N->getOperand(0);
22023   SDValue N1 = N->getOperand(1);
22024   EVT VT = N->getValueType(0);
22025
22026   // Don't create instructions with illegal types after legalize types has run.
22027   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22028   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22029     return SDValue();
22030
22031   // If we have legalized the vector types, look for blends of FADD and FSUB
22032   // nodes that we can fuse into an ADDSUB node.
22033   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22034     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22035       return AddSub;
22036
22037   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22038   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22039       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22040     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22041
22042   // During Type Legalization, when promoting illegal vector types,
22043   // the backend might introduce new shuffle dag nodes and bitcasts.
22044   //
22045   // This code performs the following transformation:
22046   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22047   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22048   //
22049   // We do this only if both the bitcast and the BINOP dag nodes have
22050   // one use. Also, perform this transformation only if the new binary
22051   // operation is legal. This is to avoid introducing dag nodes that
22052   // potentially need to be further expanded (or custom lowered) into a
22053   // less optimal sequence of dag nodes.
22054   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22055       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22056       N0.getOpcode() == ISD::BITCAST) {
22057     SDValue BC0 = N0.getOperand(0);
22058     EVT SVT = BC0.getValueType();
22059     unsigned Opcode = BC0.getOpcode();
22060     unsigned NumElts = VT.getVectorNumElements();
22061
22062     if (BC0.hasOneUse() && SVT.isVector() &&
22063         SVT.getVectorNumElements() * 2 == NumElts &&
22064         TLI.isOperationLegal(Opcode, VT)) {
22065       bool CanFold = false;
22066       switch (Opcode) {
22067       default : break;
22068       case ISD::ADD :
22069       case ISD::FADD :
22070       case ISD::SUB :
22071       case ISD::FSUB :
22072       case ISD::MUL :
22073       case ISD::FMUL :
22074         CanFold = true;
22075       }
22076
22077       unsigned SVTNumElts = SVT.getVectorNumElements();
22078       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22079       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22080         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22081       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22082         CanFold = SVOp->getMaskElt(i) < 0;
22083
22084       if (CanFold) {
22085         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22086         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22087         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22088         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22089       }
22090     }
22091   }
22092
22093   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22094   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22095   // consecutive, non-overlapping, and in the right order.
22096   SmallVector<SDValue, 16> Elts;
22097   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22098     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22099
22100   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22101     return LD;
22102
22103   if (isTargetShuffle(N->getOpcode())) {
22104     SDValue Shuffle =
22105         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22106     if (Shuffle.getNode())
22107       return Shuffle;
22108
22109     // Try recursively combining arbitrary sequences of x86 shuffle
22110     // instructions into higher-order shuffles. We do this after combining
22111     // specific PSHUF instruction sequences into their minimal form so that we
22112     // can evaluate how many specialized shuffle instructions are involved in
22113     // a particular chain.
22114     SmallVector<int, 1> NonceMask; // Just a placeholder.
22115     NonceMask.push_back(0);
22116     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22117                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22118                                       DCI, Subtarget))
22119       return SDValue(); // This routine will use CombineTo to replace N.
22120   }
22121
22122   return SDValue();
22123 }
22124
22125 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22126 /// specific shuffle of a load can be folded into a single element load.
22127 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22128 /// shuffles have been custom lowered so we need to handle those here.
22129 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22130                                          TargetLowering::DAGCombinerInfo &DCI) {
22131   if (DCI.isBeforeLegalizeOps())
22132     return SDValue();
22133
22134   SDValue InVec = N->getOperand(0);
22135   SDValue EltNo = N->getOperand(1);
22136
22137   if (!isa<ConstantSDNode>(EltNo))
22138     return SDValue();
22139
22140   EVT OriginalVT = InVec.getValueType();
22141
22142   if (InVec.getOpcode() == ISD::BITCAST) {
22143     // Don't duplicate a load with other uses.
22144     if (!InVec.hasOneUse())
22145       return SDValue();
22146     EVT BCVT = InVec.getOperand(0).getValueType();
22147     if (!BCVT.isVector() ||
22148         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22149       return SDValue();
22150     InVec = InVec.getOperand(0);
22151   }
22152
22153   EVT CurrentVT = InVec.getValueType();
22154
22155   if (!isTargetShuffle(InVec.getOpcode()))
22156     return SDValue();
22157
22158   // Don't duplicate a load with other uses.
22159   if (!InVec.hasOneUse())
22160     return SDValue();
22161
22162   SmallVector<int, 16> ShuffleMask;
22163   bool UnaryShuffle;
22164   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22165                             ShuffleMask, UnaryShuffle))
22166     return SDValue();
22167
22168   // Select the input vector, guarding against out of range extract vector.
22169   unsigned NumElems = CurrentVT.getVectorNumElements();
22170   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22171   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22172   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22173                                          : InVec.getOperand(1);
22174
22175   // If inputs to shuffle are the same for both ops, then allow 2 uses
22176   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22177                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22178
22179   if (LdNode.getOpcode() == ISD::BITCAST) {
22180     // Don't duplicate a load with other uses.
22181     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22182       return SDValue();
22183
22184     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22185     LdNode = LdNode.getOperand(0);
22186   }
22187
22188   if (!ISD::isNormalLoad(LdNode.getNode()))
22189     return SDValue();
22190
22191   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22192
22193   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22194     return SDValue();
22195
22196   EVT EltVT = N->getValueType(0);
22197   // If there's a bitcast before the shuffle, check if the load type and
22198   // alignment is valid.
22199   unsigned Align = LN0->getAlignment();
22200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22201   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22202       EltVT.getTypeForEVT(*DAG.getContext()));
22203
22204   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22205     return SDValue();
22206
22207   // All checks match so transform back to vector_shuffle so that DAG combiner
22208   // can finish the job
22209   SDLoc dl(N);
22210
22211   // Create shuffle node taking into account the case that its a unary shuffle
22212   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22213                                    : InVec.getOperand(1);
22214   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22215                                  InVec.getOperand(0), Shuffle,
22216                                  &ShuffleMask[0]);
22217   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22218   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22219                      EltNo);
22220 }
22221
22222 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22223 /// special and don't usually play with other vector types, it's better to
22224 /// handle them early to be sure we emit efficient code by avoiding
22225 /// store-load conversions.
22226 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22227   if (N->getValueType(0) != MVT::x86mmx ||
22228       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22229       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22230     return SDValue();
22231
22232   SDValue V = N->getOperand(0);
22233   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22234   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22235     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22236                        N->getValueType(0), V.getOperand(0));
22237
22238   return SDValue();
22239 }
22240
22241 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22242 /// generation and convert it from being a bunch of shuffles and extracts
22243 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22244 /// storing the value and loading scalars back, while for x64 we should
22245 /// use 64-bit extracts and shifts.
22246 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22247                                          TargetLowering::DAGCombinerInfo &DCI) {
22248   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22249     return NewOp;
22250
22251   SDValue InputVector = N->getOperand(0);
22252   SDLoc dl(InputVector);
22253   // Detect mmx to i32 conversion through a v2i32 elt extract.
22254   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22255       N->getValueType(0) == MVT::i32 &&
22256       InputVector.getValueType() == MVT::v2i32) {
22257
22258     // The bitcast source is a direct mmx result.
22259     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22260     if (MMXSrc.getValueType() == MVT::x86mmx)
22261       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22262                          N->getValueType(0),
22263                          InputVector.getNode()->getOperand(0));
22264
22265     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22266     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22267     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22268         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22269         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22270         MMXSrcOp.getValueType() == MVT::v1i64 &&
22271         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22272       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22273                          N->getValueType(0),
22274                          MMXSrcOp.getOperand(0));
22275   }
22276
22277   EVT VT = N->getValueType(0);
22278
22279   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22280       InputVector.getOpcode() == ISD::BITCAST &&
22281       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22282     uint64_t ExtractedElt =
22283           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22284     uint64_t InputValue =
22285           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22286     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22287     return DAG.getConstant(Res, dl, MVT::i1);
22288   }
22289   // Only operate on vectors of 4 elements, where the alternative shuffling
22290   // gets to be more expensive.
22291   if (InputVector.getValueType() != MVT::v4i32)
22292     return SDValue();
22293
22294   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22295   // single use which is a sign-extend or zero-extend, and all elements are
22296   // used.
22297   SmallVector<SDNode *, 4> Uses;
22298   unsigned ExtractedElements = 0;
22299   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22300        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22301     if (UI.getUse().getResNo() != InputVector.getResNo())
22302       return SDValue();
22303
22304     SDNode *Extract = *UI;
22305     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22306       return SDValue();
22307
22308     if (Extract->getValueType(0) != MVT::i32)
22309       return SDValue();
22310     if (!Extract->hasOneUse())
22311       return SDValue();
22312     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22313         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22314       return SDValue();
22315     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22316       return SDValue();
22317
22318     // Record which element was extracted.
22319     ExtractedElements |=
22320       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22321
22322     Uses.push_back(Extract);
22323   }
22324
22325   // If not all the elements were used, this may not be worthwhile.
22326   if (ExtractedElements != 15)
22327     return SDValue();
22328
22329   // Ok, we've now decided to do the transformation.
22330   // If 64-bit shifts are legal, use the extract-shift sequence,
22331   // otherwise bounce the vector off the cache.
22332   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22333   SDValue Vals[4];
22334
22335   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22336     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22337     auto &DL = DAG.getDataLayout();
22338     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22339     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22340       DAG.getConstant(0, dl, VecIdxTy));
22341     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22342       DAG.getConstant(1, dl, VecIdxTy));
22343
22344     SDValue ShAmt = DAG.getConstant(
22345         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22346     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22347     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22348       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22349     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22350     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22351       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22352   } else {
22353     // Store the value to a temporary stack slot.
22354     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22355     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22356       MachinePointerInfo(), false, false, 0);
22357
22358     EVT ElementType = InputVector.getValueType().getVectorElementType();
22359     unsigned EltSize = ElementType.getSizeInBits() / 8;
22360
22361     // Replace each use (extract) with a load of the appropriate element.
22362     for (unsigned i = 0; i < 4; ++i) {
22363       uint64_t Offset = EltSize * i;
22364       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22365       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22366
22367       SDValue ScalarAddr =
22368           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22369
22370       // Load the scalar.
22371       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22372                             ScalarAddr, MachinePointerInfo(),
22373                             false, false, false, 0);
22374
22375     }
22376   }
22377
22378   // Replace the extracts
22379   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22380     UE = Uses.end(); UI != UE; ++UI) {
22381     SDNode *Extract = *UI;
22382
22383     SDValue Idx = Extract->getOperand(1);
22384     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22385     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22386   }
22387
22388   // The replacement was made in place; don't return anything.
22389   return SDValue();
22390 }
22391
22392 static SDValue
22393 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22394                                       const X86Subtarget *Subtarget) {
22395   SDLoc dl(N);
22396   SDValue Cond = N->getOperand(0);
22397   SDValue LHS = N->getOperand(1);
22398   SDValue RHS = N->getOperand(2);
22399
22400   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22401     SDValue CondSrc = Cond->getOperand(0);
22402     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22403       Cond = CondSrc->getOperand(0);
22404   }
22405
22406   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22407     return SDValue();
22408
22409   // A vselect where all conditions and data are constants can be optimized into
22410   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22411   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22412       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22413     return SDValue();
22414
22415   unsigned MaskValue = 0;
22416   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22417     return SDValue();
22418
22419   MVT VT = N->getSimpleValueType(0);
22420   unsigned NumElems = VT.getVectorNumElements();
22421   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22422   for (unsigned i = 0; i < NumElems; ++i) {
22423     // Be sure we emit undef where we can.
22424     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22425       ShuffleMask[i] = -1;
22426     else
22427       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22428   }
22429
22430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22431   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22432     return SDValue();
22433   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22434 }
22435
22436 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22437 /// nodes.
22438 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22439                                     TargetLowering::DAGCombinerInfo &DCI,
22440                                     const X86Subtarget *Subtarget) {
22441   SDLoc DL(N);
22442   SDValue Cond = N->getOperand(0);
22443   // Get the LHS/RHS of the select.
22444   SDValue LHS = N->getOperand(1);
22445   SDValue RHS = N->getOperand(2);
22446   EVT VT = LHS.getValueType();
22447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22448
22449   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22450   // instructions match the semantics of the common C idiom x<y?x:y but not
22451   // x<=y?x:y, because of how they handle negative zero (which can be
22452   // ignored in unsafe-math mode).
22453   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22454   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22455       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22456       (Subtarget->hasSSE2() ||
22457        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22458     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22459
22460     unsigned Opcode = 0;
22461     // Check for x CC y ? x : y.
22462     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22463         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22464       switch (CC) {
22465       default: break;
22466       case ISD::SETULT:
22467         // Converting this to a min would handle NaNs incorrectly, and swapping
22468         // the operands would cause it to handle comparisons between positive
22469         // and negative zero incorrectly.
22470         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22471           if (!DAG.getTarget().Options.UnsafeFPMath &&
22472               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22473             break;
22474           std::swap(LHS, RHS);
22475         }
22476         Opcode = X86ISD::FMIN;
22477         break;
22478       case ISD::SETOLE:
22479         // Converting this to a min would handle comparisons between positive
22480         // and negative zero incorrectly.
22481         if (!DAG.getTarget().Options.UnsafeFPMath &&
22482             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22483           break;
22484         Opcode = X86ISD::FMIN;
22485         break;
22486       case ISD::SETULE:
22487         // Converting this to a min would handle both negative zeros and NaNs
22488         // incorrectly, but we can swap the operands to fix both.
22489         std::swap(LHS, RHS);
22490       case ISD::SETOLT:
22491       case ISD::SETLT:
22492       case ISD::SETLE:
22493         Opcode = X86ISD::FMIN;
22494         break;
22495
22496       case ISD::SETOGE:
22497         // Converting this to a max would handle comparisons between positive
22498         // and negative zero incorrectly.
22499         if (!DAG.getTarget().Options.UnsafeFPMath &&
22500             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22501           break;
22502         Opcode = X86ISD::FMAX;
22503         break;
22504       case ISD::SETUGT:
22505         // Converting this to a max would handle NaNs incorrectly, and swapping
22506         // the operands would cause it to handle comparisons between positive
22507         // and negative zero incorrectly.
22508         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22509           if (!DAG.getTarget().Options.UnsafeFPMath &&
22510               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22511             break;
22512           std::swap(LHS, RHS);
22513         }
22514         Opcode = X86ISD::FMAX;
22515         break;
22516       case ISD::SETUGE:
22517         // Converting this to a max would handle both negative zeros and NaNs
22518         // incorrectly, but we can swap the operands to fix both.
22519         std::swap(LHS, RHS);
22520       case ISD::SETOGT:
22521       case ISD::SETGT:
22522       case ISD::SETGE:
22523         Opcode = X86ISD::FMAX;
22524         break;
22525       }
22526     // Check for x CC y ? y : x -- a min/max with reversed arms.
22527     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22528                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22529       switch (CC) {
22530       default: break;
22531       case ISD::SETOGE:
22532         // Converting this to a min would handle comparisons between positive
22533         // and negative zero incorrectly, and swapping the operands would
22534         // cause it to handle NaNs incorrectly.
22535         if (!DAG.getTarget().Options.UnsafeFPMath &&
22536             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22537           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22538             break;
22539           std::swap(LHS, RHS);
22540         }
22541         Opcode = X86ISD::FMIN;
22542         break;
22543       case ISD::SETUGT:
22544         // Converting this to a min would handle NaNs incorrectly.
22545         if (!DAG.getTarget().Options.UnsafeFPMath &&
22546             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22547           break;
22548         Opcode = X86ISD::FMIN;
22549         break;
22550       case ISD::SETUGE:
22551         // Converting this to a min would handle both negative zeros and NaNs
22552         // incorrectly, but we can swap the operands to fix both.
22553         std::swap(LHS, RHS);
22554       case ISD::SETOGT:
22555       case ISD::SETGT:
22556       case ISD::SETGE:
22557         Opcode = X86ISD::FMIN;
22558         break;
22559
22560       case ISD::SETULT:
22561         // Converting this to a max would handle NaNs incorrectly.
22562         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22563           break;
22564         Opcode = X86ISD::FMAX;
22565         break;
22566       case ISD::SETOLE:
22567         // Converting this to a max would handle comparisons between positive
22568         // and negative zero incorrectly, and swapping the operands would
22569         // cause it to handle NaNs incorrectly.
22570         if (!DAG.getTarget().Options.UnsafeFPMath &&
22571             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22572           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22573             break;
22574           std::swap(LHS, RHS);
22575         }
22576         Opcode = X86ISD::FMAX;
22577         break;
22578       case ISD::SETULE:
22579         // Converting this to a max would handle both negative zeros and NaNs
22580         // incorrectly, but we can swap the operands to fix both.
22581         std::swap(LHS, RHS);
22582       case ISD::SETOLT:
22583       case ISD::SETLT:
22584       case ISD::SETLE:
22585         Opcode = X86ISD::FMAX;
22586         break;
22587       }
22588     }
22589
22590     if (Opcode)
22591       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22592   }
22593
22594   EVT CondVT = Cond.getValueType();
22595   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22596       CondVT.getVectorElementType() == MVT::i1) {
22597     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22598     // lowering on KNL. In this case we convert it to
22599     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22600     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22601     // Since SKX these selects have a proper lowering.
22602     EVT OpVT = LHS.getValueType();
22603     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22604         (OpVT.getVectorElementType() == MVT::i8 ||
22605          OpVT.getVectorElementType() == MVT::i16) &&
22606         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22607       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22608       DCI.AddToWorklist(Cond.getNode());
22609       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22610     }
22611   }
22612   // If this is a select between two integer constants, try to do some
22613   // optimizations.
22614   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22615     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22616       // Don't do this for crazy integer types.
22617       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22618         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22619         // so that TrueC (the true value) is larger than FalseC.
22620         bool NeedsCondInvert = false;
22621
22622         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22623             // Efficiently invertible.
22624             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22625              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22626               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22627           NeedsCondInvert = true;
22628           std::swap(TrueC, FalseC);
22629         }
22630
22631         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22632         if (FalseC->getAPIntValue() == 0 &&
22633             TrueC->getAPIntValue().isPowerOf2()) {
22634           if (NeedsCondInvert) // Invert the condition if needed.
22635             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22636                                DAG.getConstant(1, DL, Cond.getValueType()));
22637
22638           // Zero extend the condition if needed.
22639           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22640
22641           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22642           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22643                              DAG.getConstant(ShAmt, DL, MVT::i8));
22644         }
22645
22646         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22647         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22648           if (NeedsCondInvert) // Invert the condition if needed.
22649             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22650                                DAG.getConstant(1, DL, Cond.getValueType()));
22651
22652           // Zero extend the condition if needed.
22653           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22654                              FalseC->getValueType(0), Cond);
22655           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22656                              SDValue(FalseC, 0));
22657         }
22658
22659         // Optimize cases that will turn into an LEA instruction.  This requires
22660         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22661         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22662           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22663           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22664
22665           bool isFastMultiplier = false;
22666           if (Diff < 10) {
22667             switch ((unsigned char)Diff) {
22668               default: break;
22669               case 1:  // result = add base, cond
22670               case 2:  // result = lea base(    , cond*2)
22671               case 3:  // result = lea base(cond, cond*2)
22672               case 4:  // result = lea base(    , cond*4)
22673               case 5:  // result = lea base(cond, cond*4)
22674               case 8:  // result = lea base(    , cond*8)
22675               case 9:  // result = lea base(cond, cond*8)
22676                 isFastMultiplier = true;
22677                 break;
22678             }
22679           }
22680
22681           if (isFastMultiplier) {
22682             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22683             if (NeedsCondInvert) // Invert the condition if needed.
22684               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22685                                  DAG.getConstant(1, DL, Cond.getValueType()));
22686
22687             // Zero extend the condition if needed.
22688             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22689                                Cond);
22690             // Scale the condition by the difference.
22691             if (Diff != 1)
22692               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22693                                  DAG.getConstant(Diff, DL,
22694                                                  Cond.getValueType()));
22695
22696             // Add the base if non-zero.
22697             if (FalseC->getAPIntValue() != 0)
22698               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22699                                  SDValue(FalseC, 0));
22700             return Cond;
22701           }
22702         }
22703       }
22704   }
22705
22706   // Canonicalize max and min:
22707   // (x > y) ? x : y -> (x >= y) ? x : y
22708   // (x < y) ? x : y -> (x <= y) ? x : y
22709   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22710   // the need for an extra compare
22711   // against zero. e.g.
22712   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22713   // subl   %esi, %edi
22714   // testl  %edi, %edi
22715   // movl   $0, %eax
22716   // cmovgl %edi, %eax
22717   // =>
22718   // xorl   %eax, %eax
22719   // subl   %esi, $edi
22720   // cmovsl %eax, %edi
22721   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22722       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22723       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22724     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22725     switch (CC) {
22726     default: break;
22727     case ISD::SETLT:
22728     case ISD::SETGT: {
22729       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22730       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22731                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22732       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22733     }
22734     }
22735   }
22736
22737   // Early exit check
22738   if (!TLI.isTypeLegal(VT))
22739     return SDValue();
22740
22741   // Match VSELECTs into subs with unsigned saturation.
22742   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22743       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22744       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22745        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22746     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22747
22748     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22749     // left side invert the predicate to simplify logic below.
22750     SDValue Other;
22751     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22752       Other = RHS;
22753       CC = ISD::getSetCCInverse(CC, true);
22754     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22755       Other = LHS;
22756     }
22757
22758     if (Other.getNode() && Other->getNumOperands() == 2 &&
22759         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22760       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22761       SDValue CondRHS = Cond->getOperand(1);
22762
22763       // Look for a general sub with unsigned saturation first.
22764       // x >= y ? x-y : 0 --> subus x, y
22765       // x >  y ? x-y : 0 --> subus x, y
22766       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22767           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22768         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22769
22770       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22771         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22772           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22773             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22774               // If the RHS is a constant we have to reverse the const
22775               // canonicalization.
22776               // x > C-1 ? x+-C : 0 --> subus x, C
22777               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22778                   CondRHSConst->getAPIntValue() ==
22779                       (-OpRHSConst->getAPIntValue() - 1))
22780                 return DAG.getNode(
22781                     X86ISD::SUBUS, DL, VT, OpLHS,
22782                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22783
22784           // Another special case: If C was a sign bit, the sub has been
22785           // canonicalized into a xor.
22786           // FIXME: Would it be better to use computeKnownBits to determine
22787           //        whether it's safe to decanonicalize the xor?
22788           // x s< 0 ? x^C : 0 --> subus x, C
22789           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22790               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22791               OpRHSConst->getAPIntValue().isSignBit())
22792             // Note that we have to rebuild the RHS constant here to ensure we
22793             // don't rely on particular values of undef lanes.
22794             return DAG.getNode(
22795                 X86ISD::SUBUS, DL, VT, OpLHS,
22796                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22797         }
22798     }
22799   }
22800
22801   // Simplify vector selection if condition value type matches vselect
22802   // operand type
22803   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22804     assert(Cond.getValueType().isVector() &&
22805            "vector select expects a vector selector!");
22806
22807     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22808     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22809
22810     // Try invert the condition if true value is not all 1s and false value
22811     // is not all 0s.
22812     if (!TValIsAllOnes && !FValIsAllZeros &&
22813         // Check if the selector will be produced by CMPP*/PCMP*
22814         Cond.getOpcode() == ISD::SETCC &&
22815         // Check if SETCC has already been promoted
22816         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22817             CondVT) {
22818       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22819       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22820
22821       if (TValIsAllZeros || FValIsAllOnes) {
22822         SDValue CC = Cond.getOperand(2);
22823         ISD::CondCode NewCC =
22824           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22825                                Cond.getOperand(0).getValueType().isInteger());
22826         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22827         std::swap(LHS, RHS);
22828         TValIsAllOnes = FValIsAllOnes;
22829         FValIsAllZeros = TValIsAllZeros;
22830       }
22831     }
22832
22833     if (TValIsAllOnes || FValIsAllZeros) {
22834       SDValue Ret;
22835
22836       if (TValIsAllOnes && FValIsAllZeros)
22837         Ret = Cond;
22838       else if (TValIsAllOnes)
22839         Ret =
22840             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22841       else if (FValIsAllZeros)
22842         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22843                           DAG.getBitcast(CondVT, LHS));
22844
22845       return DAG.getBitcast(VT, Ret);
22846     }
22847   }
22848
22849   // We should generate an X86ISD::BLENDI from a vselect if its argument
22850   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22851   // constants. This specific pattern gets generated when we split a
22852   // selector for a 512 bit vector in a machine without AVX512 (but with
22853   // 256-bit vectors), during legalization:
22854   //
22855   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22856   //
22857   // Iff we find this pattern and the build_vectors are built from
22858   // constants, we translate the vselect into a shuffle_vector that we
22859   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22860   if ((N->getOpcode() == ISD::VSELECT ||
22861        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22862       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22863     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22864     if (Shuffle.getNode())
22865       return Shuffle;
22866   }
22867
22868   // If this is a *dynamic* select (non-constant condition) and we can match
22869   // this node with one of the variable blend instructions, restructure the
22870   // condition so that the blends can use the high bit of each element and use
22871   // SimplifyDemandedBits to simplify the condition operand.
22872   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22873       !DCI.isBeforeLegalize() &&
22874       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22875     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22876
22877     // Don't optimize vector selects that map to mask-registers.
22878     if (BitWidth == 1)
22879       return SDValue();
22880
22881     // We can only handle the cases where VSELECT is directly legal on the
22882     // subtarget. We custom lower VSELECT nodes with constant conditions and
22883     // this makes it hard to see whether a dynamic VSELECT will correctly
22884     // lower, so we both check the operation's status and explicitly handle the
22885     // cases where a *dynamic* blend will fail even though a constant-condition
22886     // blend could be custom lowered.
22887     // FIXME: We should find a better way to handle this class of problems.
22888     // Potentially, we should combine constant-condition vselect nodes
22889     // pre-legalization into shuffles and not mark as many types as custom
22890     // lowered.
22891     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22892       return SDValue();
22893     // FIXME: We don't support i16-element blends currently. We could and
22894     // should support them by making *all* the bits in the condition be set
22895     // rather than just the high bit and using an i8-element blend.
22896     if (VT.getScalarType() == MVT::i16)
22897       return SDValue();
22898     // Dynamic blending was only available from SSE4.1 onward.
22899     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22900       return SDValue();
22901     // Byte blends are only available in AVX2
22902     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22903         !Subtarget->hasAVX2())
22904       return SDValue();
22905
22906     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22907     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22908
22909     APInt KnownZero, KnownOne;
22910     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22911                                           DCI.isBeforeLegalizeOps());
22912     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22913         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22914                                  TLO)) {
22915       // If we changed the computation somewhere in the DAG, this change
22916       // will affect all users of Cond.
22917       // Make sure it is fine and update all the nodes so that we do not
22918       // use the generic VSELECT anymore. Otherwise, we may perform
22919       // wrong optimizations as we messed up with the actual expectation
22920       // for the vector boolean values.
22921       if (Cond != TLO.Old) {
22922         // Check all uses of that condition operand to check whether it will be
22923         // consumed by non-BLEND instructions, which may depend on all bits are
22924         // set properly.
22925         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22926              I != E; ++I)
22927           if (I->getOpcode() != ISD::VSELECT)
22928             // TODO: Add other opcodes eventually lowered into BLEND.
22929             return SDValue();
22930
22931         // Update all the users of the condition, before committing the change,
22932         // so that the VSELECT optimizations that expect the correct vector
22933         // boolean value will not be triggered.
22934         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22935              I != E; ++I)
22936           DAG.ReplaceAllUsesOfValueWith(
22937               SDValue(*I, 0),
22938               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22939                           Cond, I->getOperand(1), I->getOperand(2)));
22940         DCI.CommitTargetLoweringOpt(TLO);
22941         return SDValue();
22942       }
22943       // At this point, only Cond is changed. Change the condition
22944       // just for N to keep the opportunity to optimize all other
22945       // users their own way.
22946       DAG.ReplaceAllUsesOfValueWith(
22947           SDValue(N, 0),
22948           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22949                       TLO.New, N->getOperand(1), N->getOperand(2)));
22950       return SDValue();
22951     }
22952   }
22953
22954   return SDValue();
22955 }
22956
22957 // Check whether a boolean test is testing a boolean value generated by
22958 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22959 // code.
22960 //
22961 // Simplify the following patterns:
22962 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22963 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22964 // to (Op EFLAGS Cond)
22965 //
22966 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22967 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22968 // to (Op EFLAGS !Cond)
22969 //
22970 // where Op could be BRCOND or CMOV.
22971 //
22972 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22973   // Quit if not CMP and SUB with its value result used.
22974   if (Cmp.getOpcode() != X86ISD::CMP &&
22975       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22976       return SDValue();
22977
22978   // Quit if not used as a boolean value.
22979   if (CC != X86::COND_E && CC != X86::COND_NE)
22980     return SDValue();
22981
22982   // Check CMP operands. One of them should be 0 or 1 and the other should be
22983   // an SetCC or extended from it.
22984   SDValue Op1 = Cmp.getOperand(0);
22985   SDValue Op2 = Cmp.getOperand(1);
22986
22987   SDValue SetCC;
22988   const ConstantSDNode* C = nullptr;
22989   bool needOppositeCond = (CC == X86::COND_E);
22990   bool checkAgainstTrue = false; // Is it a comparison against 1?
22991
22992   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22993     SetCC = Op2;
22994   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22995     SetCC = Op1;
22996   else // Quit if all operands are not constants.
22997     return SDValue();
22998
22999   if (C->getZExtValue() == 1) {
23000     needOppositeCond = !needOppositeCond;
23001     checkAgainstTrue = true;
23002   } else if (C->getZExtValue() != 0)
23003     // Quit if the constant is neither 0 or 1.
23004     return SDValue();
23005
23006   bool truncatedToBoolWithAnd = false;
23007   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23008   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23009          SetCC.getOpcode() == ISD::TRUNCATE ||
23010          SetCC.getOpcode() == ISD::AND) {
23011     if (SetCC.getOpcode() == ISD::AND) {
23012       int OpIdx = -1;
23013       ConstantSDNode *CS;
23014       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23015           CS->getZExtValue() == 1)
23016         OpIdx = 1;
23017       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23018           CS->getZExtValue() == 1)
23019         OpIdx = 0;
23020       if (OpIdx == -1)
23021         break;
23022       SetCC = SetCC.getOperand(OpIdx);
23023       truncatedToBoolWithAnd = true;
23024     } else
23025       SetCC = SetCC.getOperand(0);
23026   }
23027
23028   switch (SetCC.getOpcode()) {
23029   case X86ISD::SETCC_CARRY:
23030     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23031     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23032     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23033     // truncated to i1 using 'and'.
23034     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23035       break;
23036     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23037            "Invalid use of SETCC_CARRY!");
23038     // FALL THROUGH
23039   case X86ISD::SETCC:
23040     // Set the condition code or opposite one if necessary.
23041     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23042     if (needOppositeCond)
23043       CC = X86::GetOppositeBranchCondition(CC);
23044     return SetCC.getOperand(1);
23045   case X86ISD::CMOV: {
23046     // Check whether false/true value has canonical one, i.e. 0 or 1.
23047     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23048     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23049     // Quit if true value is not a constant.
23050     if (!TVal)
23051       return SDValue();
23052     // Quit if false value is not a constant.
23053     if (!FVal) {
23054       SDValue Op = SetCC.getOperand(0);
23055       // Skip 'zext' or 'trunc' node.
23056       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23057           Op.getOpcode() == ISD::TRUNCATE)
23058         Op = Op.getOperand(0);
23059       // A special case for rdrand/rdseed, where 0 is set if false cond is
23060       // found.
23061       if ((Op.getOpcode() != X86ISD::RDRAND &&
23062            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23063         return SDValue();
23064     }
23065     // Quit if false value is not the constant 0 or 1.
23066     bool FValIsFalse = true;
23067     if (FVal && FVal->getZExtValue() != 0) {
23068       if (FVal->getZExtValue() != 1)
23069         return SDValue();
23070       // If FVal is 1, opposite cond is needed.
23071       needOppositeCond = !needOppositeCond;
23072       FValIsFalse = false;
23073     }
23074     // Quit if TVal is not the constant opposite of FVal.
23075     if (FValIsFalse && TVal->getZExtValue() != 1)
23076       return SDValue();
23077     if (!FValIsFalse && TVal->getZExtValue() != 0)
23078       return SDValue();
23079     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23080     if (needOppositeCond)
23081       CC = X86::GetOppositeBranchCondition(CC);
23082     return SetCC.getOperand(3);
23083   }
23084   }
23085
23086   return SDValue();
23087 }
23088
23089 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23090 /// Match:
23091 ///   (X86or (X86setcc) (X86setcc))
23092 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23093 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23094                                            X86::CondCode &CC1, SDValue &Flags,
23095                                            bool &isAnd) {
23096   if (Cond->getOpcode() == X86ISD::CMP) {
23097     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23098     if (!CondOp1C || !CondOp1C->isNullValue())
23099       return false;
23100
23101     Cond = Cond->getOperand(0);
23102   }
23103
23104   isAnd = false;
23105
23106   SDValue SetCC0, SetCC1;
23107   switch (Cond->getOpcode()) {
23108   default: return false;
23109   case ISD::AND:
23110   case X86ISD::AND:
23111     isAnd = true;
23112     // fallthru
23113   case ISD::OR:
23114   case X86ISD::OR:
23115     SetCC0 = Cond->getOperand(0);
23116     SetCC1 = Cond->getOperand(1);
23117     break;
23118   };
23119
23120   // Make sure we have SETCC nodes, using the same flags value.
23121   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23122       SetCC1.getOpcode() != X86ISD::SETCC ||
23123       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23124     return false;
23125
23126   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23127   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23128   Flags = SetCC0->getOperand(1);
23129   return true;
23130 }
23131
23132 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23133 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23134                                   TargetLowering::DAGCombinerInfo &DCI,
23135                                   const X86Subtarget *Subtarget) {
23136   SDLoc DL(N);
23137
23138   // If the flag operand isn't dead, don't touch this CMOV.
23139   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23140     return SDValue();
23141
23142   SDValue FalseOp = N->getOperand(0);
23143   SDValue TrueOp = N->getOperand(1);
23144   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23145   SDValue Cond = N->getOperand(3);
23146
23147   if (CC == X86::COND_E || CC == X86::COND_NE) {
23148     switch (Cond.getOpcode()) {
23149     default: break;
23150     case X86ISD::BSR:
23151     case X86ISD::BSF:
23152       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23153       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23154         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23155     }
23156   }
23157
23158   SDValue Flags;
23159
23160   Flags = checkBoolTestSetCCCombine(Cond, CC);
23161   if (Flags.getNode() &&
23162       // Extra check as FCMOV only supports a subset of X86 cond.
23163       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23164     SDValue Ops[] = { FalseOp, TrueOp,
23165                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23166     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23167   }
23168
23169   // If this is a select between two integer constants, try to do some
23170   // optimizations.  Note that the operands are ordered the opposite of SELECT
23171   // operands.
23172   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23173     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23174       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23175       // larger than FalseC (the false value).
23176       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23177         CC = X86::GetOppositeBranchCondition(CC);
23178         std::swap(TrueC, FalseC);
23179         std::swap(TrueOp, FalseOp);
23180       }
23181
23182       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23183       // This is efficient for any integer data type (including i8/i16) and
23184       // shift amount.
23185       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23186         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23187                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23188
23189         // Zero extend the condition if needed.
23190         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23191
23192         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23193         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23194                            DAG.getConstant(ShAmt, DL, MVT::i8));
23195         if (N->getNumValues() == 2)  // Dead flag value?
23196           return DCI.CombineTo(N, Cond, SDValue());
23197         return Cond;
23198       }
23199
23200       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23201       // for any integer data type, including i8/i16.
23202       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23203         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23204                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23205
23206         // Zero extend the condition if needed.
23207         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23208                            FalseC->getValueType(0), Cond);
23209         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23210                            SDValue(FalseC, 0));
23211
23212         if (N->getNumValues() == 2)  // Dead flag value?
23213           return DCI.CombineTo(N, Cond, SDValue());
23214         return Cond;
23215       }
23216
23217       // Optimize cases that will turn into an LEA instruction.  This requires
23218       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23219       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23220         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23221         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23222
23223         bool isFastMultiplier = false;
23224         if (Diff < 10) {
23225           switch ((unsigned char)Diff) {
23226           default: break;
23227           case 1:  // result = add base, cond
23228           case 2:  // result = lea base(    , cond*2)
23229           case 3:  // result = lea base(cond, cond*2)
23230           case 4:  // result = lea base(    , cond*4)
23231           case 5:  // result = lea base(cond, cond*4)
23232           case 8:  // result = lea base(    , cond*8)
23233           case 9:  // result = lea base(cond, cond*8)
23234             isFastMultiplier = true;
23235             break;
23236           }
23237         }
23238
23239         if (isFastMultiplier) {
23240           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23241           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23242                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23243           // Zero extend the condition if needed.
23244           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23245                              Cond);
23246           // Scale the condition by the difference.
23247           if (Diff != 1)
23248             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23249                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23250
23251           // Add the base if non-zero.
23252           if (FalseC->getAPIntValue() != 0)
23253             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23254                                SDValue(FalseC, 0));
23255           if (N->getNumValues() == 2)  // Dead flag value?
23256             return DCI.CombineTo(N, Cond, SDValue());
23257           return Cond;
23258         }
23259       }
23260     }
23261   }
23262
23263   // Handle these cases:
23264   //   (select (x != c), e, c) -> select (x != c), e, x),
23265   //   (select (x == c), c, e) -> select (x == c), x, e)
23266   // where the c is an integer constant, and the "select" is the combination
23267   // of CMOV and CMP.
23268   //
23269   // The rationale for this change is that the conditional-move from a constant
23270   // needs two instructions, however, conditional-move from a register needs
23271   // only one instruction.
23272   //
23273   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23274   //  some instruction-combining opportunities. This opt needs to be
23275   //  postponed as late as possible.
23276   //
23277   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23278     // the DCI.xxxx conditions are provided to postpone the optimization as
23279     // late as possible.
23280
23281     ConstantSDNode *CmpAgainst = nullptr;
23282     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23283         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23284         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23285
23286       if (CC == X86::COND_NE &&
23287           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23288         CC = X86::GetOppositeBranchCondition(CC);
23289         std::swap(TrueOp, FalseOp);
23290       }
23291
23292       if (CC == X86::COND_E &&
23293           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23294         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23295                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23296         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23297       }
23298     }
23299   }
23300
23301   // Fold and/or of setcc's to double CMOV:
23302   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23303   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23304   //
23305   // This combine lets us generate:
23306   //   cmovcc1 (jcc1 if we don't have CMOV)
23307   //   cmovcc2 (same)
23308   // instead of:
23309   //   setcc1
23310   //   setcc2
23311   //   and/or
23312   //   cmovne (jne if we don't have CMOV)
23313   // When we can't use the CMOV instruction, it might increase branch
23314   // mispredicts.
23315   // When we can use CMOV, or when there is no mispredict, this improves
23316   // throughput and reduces register pressure.
23317   //
23318   if (CC == X86::COND_NE) {
23319     SDValue Flags;
23320     X86::CondCode CC0, CC1;
23321     bool isAndSetCC;
23322     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23323       if (isAndSetCC) {
23324         std::swap(FalseOp, TrueOp);
23325         CC0 = X86::GetOppositeBranchCondition(CC0);
23326         CC1 = X86::GetOppositeBranchCondition(CC1);
23327       }
23328
23329       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23330         Flags};
23331       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23332       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23333       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23334       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23335       return CMOV;
23336     }
23337   }
23338
23339   return SDValue();
23340 }
23341
23342 /// PerformMulCombine - Optimize a single multiply with constant into two
23343 /// in order to implement it with two cheaper instructions, e.g.
23344 /// LEA + SHL, LEA + LEA.
23345 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23346                                  TargetLowering::DAGCombinerInfo &DCI) {
23347   // An imul is usually smaller than the alternative sequence.
23348   if (DAG.getMachineFunction().getFunction()->optForMinSize())
23349     return SDValue();
23350
23351   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23352     return SDValue();
23353
23354   EVT VT = N->getValueType(0);
23355   if (VT != MVT::i64 && VT != MVT::i32)
23356     return SDValue();
23357
23358   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23359   if (!C)
23360     return SDValue();
23361   uint64_t MulAmt = C->getZExtValue();
23362   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23363     return SDValue();
23364
23365   uint64_t MulAmt1 = 0;
23366   uint64_t MulAmt2 = 0;
23367   if ((MulAmt % 9) == 0) {
23368     MulAmt1 = 9;
23369     MulAmt2 = MulAmt / 9;
23370   } else if ((MulAmt % 5) == 0) {
23371     MulAmt1 = 5;
23372     MulAmt2 = MulAmt / 5;
23373   } else if ((MulAmt % 3) == 0) {
23374     MulAmt1 = 3;
23375     MulAmt2 = MulAmt / 3;
23376   }
23377   if (MulAmt2 &&
23378       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23379     SDLoc DL(N);
23380
23381     if (isPowerOf2_64(MulAmt2) &&
23382         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23383       // If second multiplifer is pow2, issue it first. We want the multiply by
23384       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23385       // is an add.
23386       std::swap(MulAmt1, MulAmt2);
23387
23388     SDValue NewMul;
23389     if (isPowerOf2_64(MulAmt1))
23390       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23391                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23392     else
23393       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23394                            DAG.getConstant(MulAmt1, DL, VT));
23395
23396     if (isPowerOf2_64(MulAmt2))
23397       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23398                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23399     else
23400       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23401                            DAG.getConstant(MulAmt2, DL, VT));
23402
23403     // Do not add new nodes to DAG combiner worklist.
23404     DCI.CombineTo(N, NewMul, false);
23405   }
23406   return SDValue();
23407 }
23408
23409 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23410   SDValue N0 = N->getOperand(0);
23411   SDValue N1 = N->getOperand(1);
23412   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23413   EVT VT = N0.getValueType();
23414
23415   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23416   // since the result of setcc_c is all zero's or all ones.
23417   if (VT.isInteger() && !VT.isVector() &&
23418       N1C && N0.getOpcode() == ISD::AND &&
23419       N0.getOperand(1).getOpcode() == ISD::Constant) {
23420     SDValue N00 = N0.getOperand(0);
23421     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23422         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23423           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23424          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23425       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23426       APInt ShAmt = N1C->getAPIntValue();
23427       Mask = Mask.shl(ShAmt);
23428       if (Mask != 0) {
23429         SDLoc DL(N);
23430         return DAG.getNode(ISD::AND, DL, VT,
23431                            N00, DAG.getConstant(Mask, DL, VT));
23432       }
23433     }
23434   }
23435
23436   // Hardware support for vector shifts is sparse which makes us scalarize the
23437   // vector operations in many cases. Also, on sandybridge ADD is faster than
23438   // shl.
23439   // (shl V, 1) -> add V,V
23440   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23441     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23442       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23443       // We shift all of the values by one. In many cases we do not have
23444       // hardware support for this operation. This is better expressed as an ADD
23445       // of two values.
23446       if (N1SplatC->getAPIntValue() == 1)
23447         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23448     }
23449
23450   return SDValue();
23451 }
23452
23453 /// \brief Returns a vector of 0s if the node in input is a vector logical
23454 /// shift by a constant amount which is known to be bigger than or equal
23455 /// to the vector element size in bits.
23456 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23457                                       const X86Subtarget *Subtarget) {
23458   EVT VT = N->getValueType(0);
23459
23460   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23461       (!Subtarget->hasInt256() ||
23462        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23463     return SDValue();
23464
23465   SDValue Amt = N->getOperand(1);
23466   SDLoc DL(N);
23467   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23468     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23469       APInt ShiftAmt = AmtSplat->getAPIntValue();
23470       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23471
23472       // SSE2/AVX2 logical shifts always return a vector of 0s
23473       // if the shift amount is bigger than or equal to
23474       // the element size. The constant shift amount will be
23475       // encoded as a 8-bit immediate.
23476       if (ShiftAmt.trunc(8).uge(MaxAmount))
23477         return getZeroVector(VT, Subtarget, DAG, DL);
23478     }
23479
23480   return SDValue();
23481 }
23482
23483 /// PerformShiftCombine - Combine shifts.
23484 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23485                                    TargetLowering::DAGCombinerInfo &DCI,
23486                                    const X86Subtarget *Subtarget) {
23487   if (N->getOpcode() == ISD::SHL)
23488     if (SDValue V = PerformSHLCombine(N, DAG))
23489       return V;
23490
23491   // Try to fold this logical shift into a zero vector.
23492   if (N->getOpcode() != ISD::SRA)
23493     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23494       return V;
23495
23496   return SDValue();
23497 }
23498
23499 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23500 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23501 // and friends.  Likewise for OR -> CMPNEQSS.
23502 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23503                             TargetLowering::DAGCombinerInfo &DCI,
23504                             const X86Subtarget *Subtarget) {
23505   unsigned opcode;
23506
23507   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23508   // we're requiring SSE2 for both.
23509   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23510     SDValue N0 = N->getOperand(0);
23511     SDValue N1 = N->getOperand(1);
23512     SDValue CMP0 = N0->getOperand(1);
23513     SDValue CMP1 = N1->getOperand(1);
23514     SDLoc DL(N);
23515
23516     // The SETCCs should both refer to the same CMP.
23517     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23518       return SDValue();
23519
23520     SDValue CMP00 = CMP0->getOperand(0);
23521     SDValue CMP01 = CMP0->getOperand(1);
23522     EVT     VT    = CMP00.getValueType();
23523
23524     if (VT == MVT::f32 || VT == MVT::f64) {
23525       bool ExpectingFlags = false;
23526       // Check for any users that want flags:
23527       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23528            !ExpectingFlags && UI != UE; ++UI)
23529         switch (UI->getOpcode()) {
23530         default:
23531         case ISD::BR_CC:
23532         case ISD::BRCOND:
23533         case ISD::SELECT:
23534           ExpectingFlags = true;
23535           break;
23536         case ISD::CopyToReg:
23537         case ISD::SIGN_EXTEND:
23538         case ISD::ZERO_EXTEND:
23539         case ISD::ANY_EXTEND:
23540           break;
23541         }
23542
23543       if (!ExpectingFlags) {
23544         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23545         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23546
23547         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23548           X86::CondCode tmp = cc0;
23549           cc0 = cc1;
23550           cc1 = tmp;
23551         }
23552
23553         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23554             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23555           // FIXME: need symbolic constants for these magic numbers.
23556           // See X86ATTInstPrinter.cpp:printSSECC().
23557           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23558           if (Subtarget->hasAVX512()) {
23559             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23560                                          CMP01,
23561                                          DAG.getConstant(x86cc, DL, MVT::i8));
23562             if (N->getValueType(0) != MVT::i1)
23563               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23564                                  FSetCC);
23565             return FSetCC;
23566           }
23567           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23568                                               CMP00.getValueType(), CMP00, CMP01,
23569                                               DAG.getConstant(x86cc, DL,
23570                                                               MVT::i8));
23571
23572           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23573           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23574
23575           if (is64BitFP && !Subtarget->is64Bit()) {
23576             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23577             // 64-bit integer, since that's not a legal type. Since
23578             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23579             // bits, but can do this little dance to extract the lowest 32 bits
23580             // and work with those going forward.
23581             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23582                                            OnesOrZeroesF);
23583             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23584             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23585                                         Vector32, DAG.getIntPtrConstant(0, DL));
23586             IntVT = MVT::i32;
23587           }
23588
23589           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23590           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23591                                       DAG.getConstant(1, DL, IntVT));
23592           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23593                                               ANDed);
23594           return OneBitOfTruth;
23595         }
23596       }
23597     }
23598   }
23599   return SDValue();
23600 }
23601
23602 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23603 /// so it can be folded inside ANDNP.
23604 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23605   EVT VT = N->getValueType(0);
23606
23607   // Match direct AllOnes for 128 and 256-bit vectors
23608   if (ISD::isBuildVectorAllOnes(N))
23609     return true;
23610
23611   // Look through a bit convert.
23612   if (N->getOpcode() == ISD::BITCAST)
23613     N = N->getOperand(0).getNode();
23614
23615   // Sometimes the operand may come from a insert_subvector building a 256-bit
23616   // allones vector
23617   if (VT.is256BitVector() &&
23618       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23619     SDValue V1 = N->getOperand(0);
23620     SDValue V2 = N->getOperand(1);
23621
23622     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23623         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23624         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23625         ISD::isBuildVectorAllOnes(V2.getNode()))
23626       return true;
23627   }
23628
23629   return false;
23630 }
23631
23632 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23633 // register. In most cases we actually compare or select YMM-sized registers
23634 // and mixing the two types creates horrible code. This method optimizes
23635 // some of the transition sequences.
23636 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23637                                  TargetLowering::DAGCombinerInfo &DCI,
23638                                  const X86Subtarget *Subtarget) {
23639   EVT VT = N->getValueType(0);
23640   if (!VT.is256BitVector())
23641     return SDValue();
23642
23643   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23644           N->getOpcode() == ISD::ZERO_EXTEND ||
23645           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23646
23647   SDValue Narrow = N->getOperand(0);
23648   EVT NarrowVT = Narrow->getValueType(0);
23649   if (!NarrowVT.is128BitVector())
23650     return SDValue();
23651
23652   if (Narrow->getOpcode() != ISD::XOR &&
23653       Narrow->getOpcode() != ISD::AND &&
23654       Narrow->getOpcode() != ISD::OR)
23655     return SDValue();
23656
23657   SDValue N0  = Narrow->getOperand(0);
23658   SDValue N1  = Narrow->getOperand(1);
23659   SDLoc DL(Narrow);
23660
23661   // The Left side has to be a trunc.
23662   if (N0.getOpcode() != ISD::TRUNCATE)
23663     return SDValue();
23664
23665   // The type of the truncated inputs.
23666   EVT WideVT = N0->getOperand(0)->getValueType(0);
23667   if (WideVT != VT)
23668     return SDValue();
23669
23670   // The right side has to be a 'trunc' or a constant vector.
23671   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23672   ConstantSDNode *RHSConstSplat = nullptr;
23673   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23674     RHSConstSplat = RHSBV->getConstantSplatNode();
23675   if (!RHSTrunc && !RHSConstSplat)
23676     return SDValue();
23677
23678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23679
23680   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23681     return SDValue();
23682
23683   // Set N0 and N1 to hold the inputs to the new wide operation.
23684   N0 = N0->getOperand(0);
23685   if (RHSConstSplat) {
23686     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23687                      SDValue(RHSConstSplat, 0));
23688     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23689     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23690   } else if (RHSTrunc) {
23691     N1 = N1->getOperand(0);
23692   }
23693
23694   // Generate the wide operation.
23695   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23696   unsigned Opcode = N->getOpcode();
23697   switch (Opcode) {
23698   case ISD::ANY_EXTEND:
23699     return Op;
23700   case ISD::ZERO_EXTEND: {
23701     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23702     APInt Mask = APInt::getAllOnesValue(InBits);
23703     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23704     return DAG.getNode(ISD::AND, DL, VT,
23705                        Op, DAG.getConstant(Mask, DL, VT));
23706   }
23707   case ISD::SIGN_EXTEND:
23708     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23709                        Op, DAG.getValueType(NarrowVT));
23710   default:
23711     llvm_unreachable("Unexpected opcode");
23712   }
23713 }
23714
23715 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23716                                  TargetLowering::DAGCombinerInfo &DCI,
23717                                  const X86Subtarget *Subtarget) {
23718   SDValue N0 = N->getOperand(0);
23719   SDValue N1 = N->getOperand(1);
23720   SDLoc DL(N);
23721
23722   // A vector zext_in_reg may be represented as a shuffle,
23723   // feeding into a bitcast (this represents anyext) feeding into
23724   // an and with a mask.
23725   // We'd like to try to combine that into a shuffle with zero
23726   // plus a bitcast, removing the and.
23727   if (N0.getOpcode() != ISD::BITCAST ||
23728       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23729     return SDValue();
23730
23731   // The other side of the AND should be a splat of 2^C, where C
23732   // is the number of bits in the source type.
23733   if (N1.getOpcode() == ISD::BITCAST)
23734     N1 = N1.getOperand(0);
23735   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23736     return SDValue();
23737   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23738
23739   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23740   EVT SrcType = Shuffle->getValueType(0);
23741
23742   // We expect a single-source shuffle
23743   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23744     return SDValue();
23745
23746   unsigned SrcSize = SrcType.getScalarSizeInBits();
23747
23748   APInt SplatValue, SplatUndef;
23749   unsigned SplatBitSize;
23750   bool HasAnyUndefs;
23751   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23752                                 SplatBitSize, HasAnyUndefs))
23753     return SDValue();
23754
23755   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23756   // Make sure the splat matches the mask we expect
23757   if (SplatBitSize > ResSize ||
23758       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23759     return SDValue();
23760
23761   // Make sure the input and output size make sense
23762   if (SrcSize >= ResSize || ResSize % SrcSize)
23763     return SDValue();
23764
23765   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23766   // The number of u's between each two values depends on the ratio between
23767   // the source and dest type.
23768   unsigned ZextRatio = ResSize / SrcSize;
23769   bool IsZext = true;
23770   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23771     if (i % ZextRatio) {
23772       if (Shuffle->getMaskElt(i) > 0) {
23773         // Expected undef
23774         IsZext = false;
23775         break;
23776       }
23777     } else {
23778       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23779         // Expected element number
23780         IsZext = false;
23781         break;
23782       }
23783     }
23784   }
23785
23786   if (!IsZext)
23787     return SDValue();
23788
23789   // Ok, perform the transformation - replace the shuffle with
23790   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23791   // (instead of undef) where the k elements come from the zero vector.
23792   SmallVector<int, 8> Mask;
23793   unsigned NumElems = SrcType.getVectorNumElements();
23794   for (unsigned i = 0; i < NumElems; ++i)
23795     if (i % ZextRatio)
23796       Mask.push_back(NumElems);
23797     else
23798       Mask.push_back(i / ZextRatio);
23799
23800   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23801     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23802   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23803 }
23804
23805 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23806                                  TargetLowering::DAGCombinerInfo &DCI,
23807                                  const X86Subtarget *Subtarget) {
23808   if (DCI.isBeforeLegalizeOps())
23809     return SDValue();
23810
23811   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23812     return Zext;
23813
23814   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23815     return R;
23816
23817   EVT VT = N->getValueType(0);
23818   SDValue N0 = N->getOperand(0);
23819   SDValue N1 = N->getOperand(1);
23820   SDLoc DL(N);
23821
23822   // Create BEXTR instructions
23823   // BEXTR is ((X >> imm) & (2**size-1))
23824   if (VT == MVT::i32 || VT == MVT::i64) {
23825     // Check for BEXTR.
23826     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23827         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23828       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23829       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23830       if (MaskNode && ShiftNode) {
23831         uint64_t Mask = MaskNode->getZExtValue();
23832         uint64_t Shift = ShiftNode->getZExtValue();
23833         if (isMask_64(Mask)) {
23834           uint64_t MaskSize = countPopulation(Mask);
23835           if (Shift + MaskSize <= VT.getSizeInBits())
23836             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23837                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23838                                                VT));
23839         }
23840       }
23841     } // BEXTR
23842
23843     return SDValue();
23844   }
23845
23846   // Want to form ANDNP nodes:
23847   // 1) In the hopes of then easily combining them with OR and AND nodes
23848   //    to form PBLEND/PSIGN.
23849   // 2) To match ANDN packed intrinsics
23850   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23851     return SDValue();
23852
23853   // Check LHS for vnot
23854   if (N0.getOpcode() == ISD::XOR &&
23855       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23856       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23857     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23858
23859   // Check RHS for vnot
23860   if (N1.getOpcode() == ISD::XOR &&
23861       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23862       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23863     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23864
23865   return SDValue();
23866 }
23867
23868 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23869                                 TargetLowering::DAGCombinerInfo &DCI,
23870                                 const X86Subtarget *Subtarget) {
23871   if (DCI.isBeforeLegalizeOps())
23872     return SDValue();
23873
23874   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23875     return R;
23876
23877   SDValue N0 = N->getOperand(0);
23878   SDValue N1 = N->getOperand(1);
23879   EVT VT = N->getValueType(0);
23880
23881   // look for psign/blend
23882   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23883     if (!Subtarget->hasSSSE3() ||
23884         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23885       return SDValue();
23886
23887     // Canonicalize pandn to RHS
23888     if (N0.getOpcode() == X86ISD::ANDNP)
23889       std::swap(N0, N1);
23890     // or (and (m, y), (pandn m, x))
23891     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23892       SDValue Mask = N1.getOperand(0);
23893       SDValue X    = N1.getOperand(1);
23894       SDValue Y;
23895       if (N0.getOperand(0) == Mask)
23896         Y = N0.getOperand(1);
23897       if (N0.getOperand(1) == Mask)
23898         Y = N0.getOperand(0);
23899
23900       // Check to see if the mask appeared in both the AND and ANDNP and
23901       if (!Y.getNode())
23902         return SDValue();
23903
23904       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23905       // Look through mask bitcast.
23906       if (Mask.getOpcode() == ISD::BITCAST)
23907         Mask = Mask.getOperand(0);
23908       if (X.getOpcode() == ISD::BITCAST)
23909         X = X.getOperand(0);
23910       if (Y.getOpcode() == ISD::BITCAST)
23911         Y = Y.getOperand(0);
23912
23913       EVT MaskVT = Mask.getValueType();
23914
23915       // Validate that the Mask operand is a vector sra node.
23916       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23917       // there is no psrai.b
23918       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23919       unsigned SraAmt = ~0;
23920       if (Mask.getOpcode() == ISD::SRA) {
23921         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23922           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23923             SraAmt = AmtConst->getZExtValue();
23924       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23925         SDValue SraC = Mask.getOperand(1);
23926         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23927       }
23928       if ((SraAmt + 1) != EltBits)
23929         return SDValue();
23930
23931       SDLoc DL(N);
23932
23933       // Now we know we at least have a plendvb with the mask val.  See if
23934       // we can form a psignb/w/d.
23935       // psign = x.type == y.type == mask.type && y = sub(0, x);
23936       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23937           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23938           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23939         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23940                "Unsupported VT for PSIGN");
23941         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23942         return DAG.getBitcast(VT, Mask);
23943       }
23944       // PBLENDVB only available on SSE 4.1
23945       if (!Subtarget->hasSSE41())
23946         return SDValue();
23947
23948       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23949
23950       X = DAG.getBitcast(BlendVT, X);
23951       Y = DAG.getBitcast(BlendVT, Y);
23952       Mask = DAG.getBitcast(BlendVT, Mask);
23953       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23954       return DAG.getBitcast(VT, Mask);
23955     }
23956   }
23957
23958   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23959     return SDValue();
23960
23961   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23962   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
23963
23964   // SHLD/SHRD instructions have lower register pressure, but on some
23965   // platforms they have higher latency than the equivalent
23966   // series of shifts/or that would otherwise be generated.
23967   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23968   // have higher latencies and we are not optimizing for size.
23969   if (!OptForSize && Subtarget->isSHLDSlow())
23970     return SDValue();
23971
23972   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23973     std::swap(N0, N1);
23974   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23975     return SDValue();
23976   if (!N0.hasOneUse() || !N1.hasOneUse())
23977     return SDValue();
23978
23979   SDValue ShAmt0 = N0.getOperand(1);
23980   if (ShAmt0.getValueType() != MVT::i8)
23981     return SDValue();
23982   SDValue ShAmt1 = N1.getOperand(1);
23983   if (ShAmt1.getValueType() != MVT::i8)
23984     return SDValue();
23985   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23986     ShAmt0 = ShAmt0.getOperand(0);
23987   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23988     ShAmt1 = ShAmt1.getOperand(0);
23989
23990   SDLoc DL(N);
23991   unsigned Opc = X86ISD::SHLD;
23992   SDValue Op0 = N0.getOperand(0);
23993   SDValue Op1 = N1.getOperand(0);
23994   if (ShAmt0.getOpcode() == ISD::SUB) {
23995     Opc = X86ISD::SHRD;
23996     std::swap(Op0, Op1);
23997     std::swap(ShAmt0, ShAmt1);
23998   }
23999
24000   unsigned Bits = VT.getSizeInBits();
24001   if (ShAmt1.getOpcode() == ISD::SUB) {
24002     SDValue Sum = ShAmt1.getOperand(0);
24003     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24004       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24005       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24006         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24007       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24008         return DAG.getNode(Opc, DL, VT,
24009                            Op0, Op1,
24010                            DAG.getNode(ISD::TRUNCATE, DL,
24011                                        MVT::i8, ShAmt0));
24012     }
24013   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24014     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24015     if (ShAmt0C &&
24016         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24017       return DAG.getNode(Opc, DL, VT,
24018                          N0.getOperand(0), N1.getOperand(0),
24019                          DAG.getNode(ISD::TRUNCATE, DL,
24020                                        MVT::i8, ShAmt0));
24021   }
24022
24023   return SDValue();
24024 }
24025
24026 // Generate NEG and CMOV for integer abs.
24027 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24028   EVT VT = N->getValueType(0);
24029
24030   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24031   // 8-bit integer abs to NEG and CMOV.
24032   if (VT.isInteger() && VT.getSizeInBits() == 8)
24033     return SDValue();
24034
24035   SDValue N0 = N->getOperand(0);
24036   SDValue N1 = N->getOperand(1);
24037   SDLoc DL(N);
24038
24039   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24040   // and change it to SUB and CMOV.
24041   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24042       N0.getOpcode() == ISD::ADD &&
24043       N0.getOperand(1) == N1 &&
24044       N1.getOpcode() == ISD::SRA &&
24045       N1.getOperand(0) == N0.getOperand(0))
24046     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24047       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24048         // Generate SUB & CMOV.
24049         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24050                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24051
24052         SDValue Ops[] = { N0.getOperand(0), Neg,
24053                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24054                           SDValue(Neg.getNode(), 1) };
24055         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24056       }
24057   return SDValue();
24058 }
24059
24060 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24061 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24062                                  TargetLowering::DAGCombinerInfo &DCI,
24063                                  const X86Subtarget *Subtarget) {
24064   if (DCI.isBeforeLegalizeOps())
24065     return SDValue();
24066
24067   if (Subtarget->hasCMov())
24068     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24069       return RV;
24070
24071   return SDValue();
24072 }
24073
24074 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24075 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24076                                   TargetLowering::DAGCombinerInfo &DCI,
24077                                   const X86Subtarget *Subtarget) {
24078   LoadSDNode *Ld = cast<LoadSDNode>(N);
24079   EVT RegVT = Ld->getValueType(0);
24080   EVT MemVT = Ld->getMemoryVT();
24081   SDLoc dl(Ld);
24082   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24083
24084   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24085   // into two 16-byte operations.
24086   ISD::LoadExtType Ext = Ld->getExtensionType();
24087   unsigned Alignment = Ld->getAlignment();
24088   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24089   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24090       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24091     unsigned NumElems = RegVT.getVectorNumElements();
24092     if (NumElems < 2)
24093       return SDValue();
24094
24095     SDValue Ptr = Ld->getBasePtr();
24096     SDValue Increment =
24097         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24098
24099     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24100                                   NumElems/2);
24101     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24102                                 Ld->getPointerInfo(), Ld->isVolatile(),
24103                                 Ld->isNonTemporal(), Ld->isInvariant(),
24104                                 Alignment);
24105     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24106     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24107                                 Ld->getPointerInfo(), Ld->isVolatile(),
24108                                 Ld->isNonTemporal(), Ld->isInvariant(),
24109                                 std::min(16U, Alignment));
24110     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24111                              Load1.getValue(1),
24112                              Load2.getValue(1));
24113
24114     SDValue NewVec = DAG.getUNDEF(RegVT);
24115     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24116     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24117     return DCI.CombineTo(N, NewVec, TF, true);
24118   }
24119
24120   return SDValue();
24121 }
24122
24123 /// PerformMLOADCombine - Resolve extending loads
24124 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24125                                    TargetLowering::DAGCombinerInfo &DCI,
24126                                    const X86Subtarget *Subtarget) {
24127   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24128   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24129     return SDValue();
24130
24131   EVT VT = Mld->getValueType(0);
24132   unsigned NumElems = VT.getVectorNumElements();
24133   EVT LdVT = Mld->getMemoryVT();
24134   SDLoc dl(Mld);
24135
24136   assert(LdVT != VT && "Cannot extend to the same type");
24137   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24138   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24139   // From, To sizes and ElemCount must be pow of two
24140   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24141     "Unexpected size for extending masked load");
24142
24143   unsigned SizeRatio  = ToSz / FromSz;
24144   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24145
24146   // Create a type on which we perform the shuffle
24147   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24148           LdVT.getScalarType(), NumElems*SizeRatio);
24149   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24150
24151   // Convert Src0 value
24152   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24153   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24154     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24155     for (unsigned i = 0; i != NumElems; ++i)
24156       ShuffleVec[i] = i * SizeRatio;
24157
24158     // Can't shuffle using an illegal type.
24159     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24160             && "WideVecVT should be legal");
24161     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24162                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24163   }
24164   // Prepare the new mask
24165   SDValue NewMask;
24166   SDValue Mask = Mld->getMask();
24167   if (Mask.getValueType() == VT) {
24168     // Mask and original value have the same type
24169     NewMask = DAG.getBitcast(WideVecVT, Mask);
24170     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24171     for (unsigned i = 0; i != NumElems; ++i)
24172       ShuffleVec[i] = i * SizeRatio;
24173     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24174       ShuffleVec[i] = NumElems*SizeRatio;
24175     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24176                                    DAG.getConstant(0, dl, WideVecVT),
24177                                    &ShuffleVec[0]);
24178   }
24179   else {
24180     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24181     unsigned WidenNumElts = NumElems*SizeRatio;
24182     unsigned MaskNumElts = VT.getVectorNumElements();
24183     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24184                                      WidenNumElts);
24185
24186     unsigned NumConcat = WidenNumElts / MaskNumElts;
24187     SmallVector<SDValue, 16> Ops(NumConcat);
24188     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24189     Ops[0] = Mask;
24190     for (unsigned i = 1; i != NumConcat; ++i)
24191       Ops[i] = ZeroVal;
24192
24193     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24194   }
24195
24196   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24197                                      Mld->getBasePtr(), NewMask, WideSrc0,
24198                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24199                                      ISD::NON_EXTLOAD);
24200   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24201   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24202
24203 }
24204 /// PerformMSTORECombine - Resolve truncating stores
24205 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24206                                     const X86Subtarget *Subtarget) {
24207   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24208   if (!Mst->isTruncatingStore())
24209     return SDValue();
24210
24211   EVT VT = Mst->getValue().getValueType();
24212   unsigned NumElems = VT.getVectorNumElements();
24213   EVT StVT = Mst->getMemoryVT();
24214   SDLoc dl(Mst);
24215
24216   assert(StVT != VT && "Cannot truncate to the same type");
24217   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24218   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24219
24220   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24221
24222   // The truncating store is legal in some cases. For example
24223   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24224   // are designated for truncate store.
24225   // In this case we don't need any further transformations.
24226   if (TLI.isTruncStoreLegal(VT, StVT))
24227     return SDValue();
24228
24229   // From, To sizes and ElemCount must be pow of two
24230   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24231     "Unexpected size for truncating masked store");
24232   // We are going to use the original vector elt for storing.
24233   // Accumulated smaller vector elements must be a multiple of the store size.
24234   assert (((NumElems * FromSz) % ToSz) == 0 &&
24235           "Unexpected ratio for truncating masked store");
24236
24237   unsigned SizeRatio  = FromSz / ToSz;
24238   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24239
24240   // Create a type on which we perform the shuffle
24241   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24242           StVT.getScalarType(), NumElems*SizeRatio);
24243
24244   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24245
24246   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24247   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24248   for (unsigned i = 0; i != NumElems; ++i)
24249     ShuffleVec[i] = i * SizeRatio;
24250
24251   // Can't shuffle using an illegal type.
24252   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24253           && "WideVecVT should be legal");
24254
24255   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24256                                         DAG.getUNDEF(WideVecVT),
24257                                         &ShuffleVec[0]);
24258
24259   SDValue NewMask;
24260   SDValue Mask = Mst->getMask();
24261   if (Mask.getValueType() == VT) {
24262     // Mask and original value have the same type
24263     NewMask = DAG.getBitcast(WideVecVT, Mask);
24264     for (unsigned i = 0; i != NumElems; ++i)
24265       ShuffleVec[i] = i * SizeRatio;
24266     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24267       ShuffleVec[i] = NumElems*SizeRatio;
24268     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24269                                    DAG.getConstant(0, dl, WideVecVT),
24270                                    &ShuffleVec[0]);
24271   }
24272   else {
24273     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24274     unsigned WidenNumElts = NumElems*SizeRatio;
24275     unsigned MaskNumElts = VT.getVectorNumElements();
24276     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24277                                      WidenNumElts);
24278
24279     unsigned NumConcat = WidenNumElts / MaskNumElts;
24280     SmallVector<SDValue, 16> Ops(NumConcat);
24281     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24282     Ops[0] = Mask;
24283     for (unsigned i = 1; i != NumConcat; ++i)
24284       Ops[i] = ZeroVal;
24285
24286     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24287   }
24288
24289   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24290                             NewMask, StVT, Mst->getMemOperand(), false);
24291 }
24292 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24293 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24294                                    const X86Subtarget *Subtarget) {
24295   StoreSDNode *St = cast<StoreSDNode>(N);
24296   EVT VT = St->getValue().getValueType();
24297   EVT StVT = St->getMemoryVT();
24298   SDLoc dl(St);
24299   SDValue StoredVal = St->getOperand(1);
24300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24301
24302   // If we are saving a concatenation of two XMM registers and 32-byte stores
24303   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24304   unsigned Alignment = St->getAlignment();
24305   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24306   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24307       StVT == VT && !IsAligned) {
24308     unsigned NumElems = VT.getVectorNumElements();
24309     if (NumElems < 2)
24310       return SDValue();
24311
24312     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24313     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24314
24315     SDValue Stride =
24316         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24317     SDValue Ptr0 = St->getBasePtr();
24318     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24319
24320     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24321                                 St->getPointerInfo(), St->isVolatile(),
24322                                 St->isNonTemporal(), Alignment);
24323     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24324                                 St->getPointerInfo(), St->isVolatile(),
24325                                 St->isNonTemporal(),
24326                                 std::min(16U, Alignment));
24327     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24328   }
24329
24330   // Optimize trunc store (of multiple scalars) to shuffle and store.
24331   // First, pack all of the elements in one place. Next, store to memory
24332   // in fewer chunks.
24333   if (St->isTruncatingStore() && VT.isVector()) {
24334     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24335     unsigned NumElems = VT.getVectorNumElements();
24336     assert(StVT != VT && "Cannot truncate to the same type");
24337     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24338     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24339
24340     // The truncating store is legal in some cases. For example
24341     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24342     // are designated for truncate store.
24343     // In this case we don't need any further transformations.
24344     if (TLI.isTruncStoreLegal(VT, StVT))
24345       return SDValue();
24346
24347     // From, To sizes and ElemCount must be pow of two
24348     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24349     // We are going to use the original vector elt for storing.
24350     // Accumulated smaller vector elements must be a multiple of the store size.
24351     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24352
24353     unsigned SizeRatio  = FromSz / ToSz;
24354
24355     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24356
24357     // Create a type on which we perform the shuffle
24358     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24359             StVT.getScalarType(), NumElems*SizeRatio);
24360
24361     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24362
24363     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24364     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24365     for (unsigned i = 0; i != NumElems; ++i)
24366       ShuffleVec[i] = i * SizeRatio;
24367
24368     // Can't shuffle using an illegal type.
24369     if (!TLI.isTypeLegal(WideVecVT))
24370       return SDValue();
24371
24372     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24373                                          DAG.getUNDEF(WideVecVT),
24374                                          &ShuffleVec[0]);
24375     // At this point all of the data is stored at the bottom of the
24376     // register. We now need to save it to mem.
24377
24378     // Find the largest store unit
24379     MVT StoreType = MVT::i8;
24380     for (MVT Tp : MVT::integer_valuetypes()) {
24381       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24382         StoreType = Tp;
24383     }
24384
24385     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24386     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24387         (64 <= NumElems * ToSz))
24388       StoreType = MVT::f64;
24389
24390     // Bitcast the original vector into a vector of store-size units
24391     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24392             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24393     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24394     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24395     SmallVector<SDValue, 8> Chains;
24396     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24397                                         TLI.getPointerTy(DAG.getDataLayout()));
24398     SDValue Ptr = St->getBasePtr();
24399
24400     // Perform one or more big stores into memory.
24401     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24402       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24403                                    StoreType, ShuffWide,
24404                                    DAG.getIntPtrConstant(i, dl));
24405       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24406                                 St->getPointerInfo(), St->isVolatile(),
24407                                 St->isNonTemporal(), St->getAlignment());
24408       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24409       Chains.push_back(Ch);
24410     }
24411
24412     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24413   }
24414
24415   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24416   // the FP state in cases where an emms may be missing.
24417   // A preferable solution to the general problem is to figure out the right
24418   // places to insert EMMS.  This qualifies as a quick hack.
24419
24420   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24421   if (VT.getSizeInBits() != 64)
24422     return SDValue();
24423
24424   const Function *F = DAG.getMachineFunction().getFunction();
24425   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24426   bool F64IsLegal =
24427       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24428   if ((VT.isVector() ||
24429        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24430       isa<LoadSDNode>(St->getValue()) &&
24431       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24432       St->getChain().hasOneUse() && !St->isVolatile()) {
24433     SDNode* LdVal = St->getValue().getNode();
24434     LoadSDNode *Ld = nullptr;
24435     int TokenFactorIndex = -1;
24436     SmallVector<SDValue, 8> Ops;
24437     SDNode* ChainVal = St->getChain().getNode();
24438     // Must be a store of a load.  We currently handle two cases:  the load
24439     // is a direct child, and it's under an intervening TokenFactor.  It is
24440     // possible to dig deeper under nested TokenFactors.
24441     if (ChainVal == LdVal)
24442       Ld = cast<LoadSDNode>(St->getChain());
24443     else if (St->getValue().hasOneUse() &&
24444              ChainVal->getOpcode() == ISD::TokenFactor) {
24445       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24446         if (ChainVal->getOperand(i).getNode() == LdVal) {
24447           TokenFactorIndex = i;
24448           Ld = cast<LoadSDNode>(St->getValue());
24449         } else
24450           Ops.push_back(ChainVal->getOperand(i));
24451       }
24452     }
24453
24454     if (!Ld || !ISD::isNormalLoad(Ld))
24455       return SDValue();
24456
24457     // If this is not the MMX case, i.e. we are just turning i64 load/store
24458     // into f64 load/store, avoid the transformation if there are multiple
24459     // uses of the loaded value.
24460     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24461       return SDValue();
24462
24463     SDLoc LdDL(Ld);
24464     SDLoc StDL(N);
24465     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24466     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24467     // pair instead.
24468     if (Subtarget->is64Bit() || F64IsLegal) {
24469       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24470       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24471                                   Ld->getPointerInfo(), Ld->isVolatile(),
24472                                   Ld->isNonTemporal(), Ld->isInvariant(),
24473                                   Ld->getAlignment());
24474       SDValue NewChain = NewLd.getValue(1);
24475       if (TokenFactorIndex != -1) {
24476         Ops.push_back(NewChain);
24477         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24478       }
24479       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24480                           St->getPointerInfo(),
24481                           St->isVolatile(), St->isNonTemporal(),
24482                           St->getAlignment());
24483     }
24484
24485     // Otherwise, lower to two pairs of 32-bit loads / stores.
24486     SDValue LoAddr = Ld->getBasePtr();
24487     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24488                                  DAG.getConstant(4, LdDL, MVT::i32));
24489
24490     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24491                                Ld->getPointerInfo(),
24492                                Ld->isVolatile(), Ld->isNonTemporal(),
24493                                Ld->isInvariant(), Ld->getAlignment());
24494     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24495                                Ld->getPointerInfo().getWithOffset(4),
24496                                Ld->isVolatile(), Ld->isNonTemporal(),
24497                                Ld->isInvariant(),
24498                                MinAlign(Ld->getAlignment(), 4));
24499
24500     SDValue NewChain = LoLd.getValue(1);
24501     if (TokenFactorIndex != -1) {
24502       Ops.push_back(LoLd);
24503       Ops.push_back(HiLd);
24504       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24505     }
24506
24507     LoAddr = St->getBasePtr();
24508     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24509                          DAG.getConstant(4, StDL, MVT::i32));
24510
24511     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24512                                 St->getPointerInfo(),
24513                                 St->isVolatile(), St->isNonTemporal(),
24514                                 St->getAlignment());
24515     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24516                                 St->getPointerInfo().getWithOffset(4),
24517                                 St->isVolatile(),
24518                                 St->isNonTemporal(),
24519                                 MinAlign(St->getAlignment(), 4));
24520     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24521   }
24522
24523   // This is similar to the above case, but here we handle a scalar 64-bit
24524   // integer store that is extracted from a vector on a 32-bit target.
24525   // If we have SSE2, then we can treat it like a floating-point double
24526   // to get past legalization. The execution dependencies fixup pass will
24527   // choose the optimal machine instruction for the store if this really is
24528   // an integer or v2f32 rather than an f64.
24529   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24530       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24531     SDValue OldExtract = St->getOperand(1);
24532     SDValue ExtOp0 = OldExtract.getOperand(0);
24533     unsigned VecSize = ExtOp0.getValueSizeInBits();
24534     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24535     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24536     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24537                                      BitCast, OldExtract.getOperand(1));
24538     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24539                         St->getPointerInfo(), St->isVolatile(),
24540                         St->isNonTemporal(), St->getAlignment());
24541   }
24542
24543   return SDValue();
24544 }
24545
24546 /// Return 'true' if this vector operation is "horizontal"
24547 /// and return the operands for the horizontal operation in LHS and RHS.  A
24548 /// horizontal operation performs the binary operation on successive elements
24549 /// of its first operand, then on successive elements of its second operand,
24550 /// returning the resulting values in a vector.  For example, if
24551 ///   A = < float a0, float a1, float a2, float a3 >
24552 /// and
24553 ///   B = < float b0, float b1, float b2, float b3 >
24554 /// then the result of doing a horizontal operation on A and B is
24555 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24556 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24557 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24558 /// set to A, RHS to B, and the routine returns 'true'.
24559 /// Note that the binary operation should have the property that if one of the
24560 /// operands is UNDEF then the result is UNDEF.
24561 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24562   // Look for the following pattern: if
24563   //   A = < float a0, float a1, float a2, float a3 >
24564   //   B = < float b0, float b1, float b2, float b3 >
24565   // and
24566   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24567   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24568   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24569   // which is A horizontal-op B.
24570
24571   // At least one of the operands should be a vector shuffle.
24572   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24573       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24574     return false;
24575
24576   MVT VT = LHS.getSimpleValueType();
24577
24578   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24579          "Unsupported vector type for horizontal add/sub");
24580
24581   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24582   // operate independently on 128-bit lanes.
24583   unsigned NumElts = VT.getVectorNumElements();
24584   unsigned NumLanes = VT.getSizeInBits()/128;
24585   unsigned NumLaneElts = NumElts / NumLanes;
24586   assert((NumLaneElts % 2 == 0) &&
24587          "Vector type should have an even number of elements in each lane");
24588   unsigned HalfLaneElts = NumLaneElts/2;
24589
24590   // View LHS in the form
24591   //   LHS = VECTOR_SHUFFLE A, B, LMask
24592   // If LHS is not a shuffle then pretend it is the shuffle
24593   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24594   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24595   // type VT.
24596   SDValue A, B;
24597   SmallVector<int, 16> LMask(NumElts);
24598   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24599     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24600       A = LHS.getOperand(0);
24601     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24602       B = LHS.getOperand(1);
24603     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24604     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24605   } else {
24606     if (LHS.getOpcode() != ISD::UNDEF)
24607       A = LHS;
24608     for (unsigned i = 0; i != NumElts; ++i)
24609       LMask[i] = i;
24610   }
24611
24612   // Likewise, view RHS in the form
24613   //   RHS = VECTOR_SHUFFLE C, D, RMask
24614   SDValue C, D;
24615   SmallVector<int, 16> RMask(NumElts);
24616   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24617     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24618       C = RHS.getOperand(0);
24619     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24620       D = RHS.getOperand(1);
24621     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24622     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24623   } else {
24624     if (RHS.getOpcode() != ISD::UNDEF)
24625       C = RHS;
24626     for (unsigned i = 0; i != NumElts; ++i)
24627       RMask[i] = i;
24628   }
24629
24630   // Check that the shuffles are both shuffling the same vectors.
24631   if (!(A == C && B == D) && !(A == D && B == C))
24632     return false;
24633
24634   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24635   if (!A.getNode() && !B.getNode())
24636     return false;
24637
24638   // If A and B occur in reverse order in RHS, then "swap" them (which means
24639   // rewriting the mask).
24640   if (A != C)
24641     ShuffleVectorSDNode::commuteMask(RMask);
24642
24643   // At this point LHS and RHS are equivalent to
24644   //   LHS = VECTOR_SHUFFLE A, B, LMask
24645   //   RHS = VECTOR_SHUFFLE A, B, RMask
24646   // Check that the masks correspond to performing a horizontal operation.
24647   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24648     for (unsigned i = 0; i != NumLaneElts; ++i) {
24649       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24650
24651       // Ignore any UNDEF components.
24652       if (LIdx < 0 || RIdx < 0 ||
24653           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24654           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24655         continue;
24656
24657       // Check that successive elements are being operated on.  If not, this is
24658       // not a horizontal operation.
24659       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24660       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24661       if (!(LIdx == Index && RIdx == Index + 1) &&
24662           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24663         return false;
24664     }
24665   }
24666
24667   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24668   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24669   return true;
24670 }
24671
24672 /// Do target-specific dag combines on floating point adds.
24673 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24674                                   const X86Subtarget *Subtarget) {
24675   EVT VT = N->getValueType(0);
24676   SDValue LHS = N->getOperand(0);
24677   SDValue RHS = N->getOperand(1);
24678
24679   // Try to synthesize horizontal adds from adds of shuffles.
24680   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24681        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24682       isHorizontalBinOp(LHS, RHS, true))
24683     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24684   return SDValue();
24685 }
24686
24687 /// Do target-specific dag combines on floating point subs.
24688 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24689                                   const X86Subtarget *Subtarget) {
24690   EVT VT = N->getValueType(0);
24691   SDValue LHS = N->getOperand(0);
24692   SDValue RHS = N->getOperand(1);
24693
24694   // Try to synthesize horizontal subs from subs of shuffles.
24695   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24696        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24697       isHorizontalBinOp(LHS, RHS, false))
24698     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24699   return SDValue();
24700 }
24701
24702 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24703 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24704   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24705
24706   // F[X]OR(0.0, x) -> x
24707   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24708     if (C->getValueAPF().isPosZero())
24709       return N->getOperand(1);
24710
24711   // F[X]OR(x, 0.0) -> x
24712   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24713     if (C->getValueAPF().isPosZero())
24714       return N->getOperand(0);
24715   return SDValue();
24716 }
24717
24718 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24719 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24720   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24721
24722   // Only perform optimizations if UnsafeMath is used.
24723   if (!DAG.getTarget().Options.UnsafeFPMath)
24724     return SDValue();
24725
24726   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24727   // into FMINC and FMAXC, which are Commutative operations.
24728   unsigned NewOp = 0;
24729   switch (N->getOpcode()) {
24730     default: llvm_unreachable("unknown opcode");
24731     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24732     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24733   }
24734
24735   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24736                      N->getOperand(0), N->getOperand(1));
24737 }
24738
24739 /// Do target-specific dag combines on X86ISD::FAND nodes.
24740 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24741   // FAND(0.0, x) -> 0.0
24742   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24743     if (C->getValueAPF().isPosZero())
24744       return N->getOperand(0);
24745
24746   // FAND(x, 0.0) -> 0.0
24747   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24748     if (C->getValueAPF().isPosZero())
24749       return N->getOperand(1);
24750
24751   return SDValue();
24752 }
24753
24754 /// Do target-specific dag combines on X86ISD::FANDN nodes
24755 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24756   // FANDN(0.0, x) -> x
24757   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24758     if (C->getValueAPF().isPosZero())
24759       return N->getOperand(1);
24760
24761   // FANDN(x, 0.0) -> 0.0
24762   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24763     if (C->getValueAPF().isPosZero())
24764       return N->getOperand(1);
24765
24766   return SDValue();
24767 }
24768
24769 static SDValue PerformBTCombine(SDNode *N,
24770                                 SelectionDAG &DAG,
24771                                 TargetLowering::DAGCombinerInfo &DCI) {
24772   // BT ignores high bits in the bit index operand.
24773   SDValue Op1 = N->getOperand(1);
24774   if (Op1.hasOneUse()) {
24775     unsigned BitWidth = Op1.getValueSizeInBits();
24776     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24777     APInt KnownZero, KnownOne;
24778     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24779                                           !DCI.isBeforeLegalizeOps());
24780     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24781     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24782         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24783       DCI.CommitTargetLoweringOpt(TLO);
24784   }
24785   return SDValue();
24786 }
24787
24788 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24789   SDValue Op = N->getOperand(0);
24790   if (Op.getOpcode() == ISD::BITCAST)
24791     Op = Op.getOperand(0);
24792   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24793   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24794       VT.getVectorElementType().getSizeInBits() ==
24795       OpVT.getVectorElementType().getSizeInBits()) {
24796     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24797   }
24798   return SDValue();
24799 }
24800
24801 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24802                                                const X86Subtarget *Subtarget) {
24803   EVT VT = N->getValueType(0);
24804   if (!VT.isVector())
24805     return SDValue();
24806
24807   SDValue N0 = N->getOperand(0);
24808   SDValue N1 = N->getOperand(1);
24809   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24810   SDLoc dl(N);
24811
24812   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24813   // both SSE and AVX2 since there is no sign-extended shift right
24814   // operation on a vector with 64-bit elements.
24815   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24816   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24817   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24818       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24819     SDValue N00 = N0.getOperand(0);
24820
24821     // EXTLOAD has a better solution on AVX2,
24822     // it may be replaced with X86ISD::VSEXT node.
24823     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24824       if (!ISD::isNormalLoad(N00.getNode()))
24825         return SDValue();
24826
24827     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24828         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24829                                   N00, N1);
24830       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24831     }
24832   }
24833   return SDValue();
24834 }
24835
24836 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24837                                   TargetLowering::DAGCombinerInfo &DCI,
24838                                   const X86Subtarget *Subtarget) {
24839   SDValue N0 = N->getOperand(0);
24840   EVT VT = N->getValueType(0);
24841   EVT SVT = VT.getScalarType();
24842   EVT InVT = N0.getValueType();
24843   EVT InSVT = InVT.getScalarType();
24844   SDLoc DL(N);
24845
24846   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24847   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24848   // This exposes the sext to the sdivrem lowering, so that it directly extends
24849   // from AH (which we otherwise need to do contortions to access).
24850   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24851       InVT == MVT::i8 && VT == MVT::i32) {
24852     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24853     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24854                             N0.getOperand(0), N0.getOperand(1));
24855     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24856     return R.getValue(1);
24857   }
24858
24859   if (!DCI.isBeforeLegalizeOps()) {
24860     if (InVT == MVT::i1) {
24861       SDValue Zero = DAG.getConstant(0, DL, VT);
24862       SDValue AllOnes =
24863         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24864       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24865     }
24866     return SDValue();
24867   }
24868
24869   if (VT.isVector() && Subtarget->hasSSE2()) {
24870     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24871       EVT InVT = N.getValueType();
24872       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24873                                    Size / InVT.getScalarSizeInBits());
24874       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24875                                     DAG.getUNDEF(InVT));
24876       Opnds[0] = N;
24877       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24878     };
24879
24880     // If target-size is less than 128-bits, extend to a type that would extend
24881     // to 128 bits, extend that and extract the original target vector.
24882     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24883         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24884         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24885       unsigned Scale = 128 / VT.getSizeInBits();
24886       EVT ExVT =
24887           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24888       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24889       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24890       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24891                          DAG.getIntPtrConstant(0, DL));
24892     }
24893
24894     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24895     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24896     if (VT.getSizeInBits() == 128 &&
24897         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24898         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24899       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24900       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24901     }
24902
24903     // On pre-AVX2 targets, split into 128-bit nodes of
24904     // ISD::SIGN_EXTEND_VECTOR_INREG.
24905     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24906         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24907         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24908       unsigned NumVecs = VT.getSizeInBits() / 128;
24909       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24910       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24911       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24912
24913       SmallVector<SDValue, 8> Opnds;
24914       for (unsigned i = 0, Offset = 0; i != NumVecs;
24915            ++i, Offset += NumSubElts) {
24916         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24917                                      DAG.getIntPtrConstant(Offset, DL));
24918         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24919         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24920         Opnds.push_back(SrcVec);
24921       }
24922       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24923     }
24924   }
24925
24926   if (!Subtarget->hasFp256())
24927     return SDValue();
24928
24929   if (VT.isVector() && VT.getSizeInBits() == 256)
24930     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24931       return R;
24932
24933   return SDValue();
24934 }
24935
24936 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24937                                  const X86Subtarget* Subtarget) {
24938   SDLoc dl(N);
24939   EVT VT = N->getValueType(0);
24940
24941   // Let legalize expand this if it isn't a legal type yet.
24942   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24943     return SDValue();
24944
24945   EVT ScalarVT = VT.getScalarType();
24946   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24947       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24948        !Subtarget->hasAVX512()))
24949     return SDValue();
24950
24951   SDValue A = N->getOperand(0);
24952   SDValue B = N->getOperand(1);
24953   SDValue C = N->getOperand(2);
24954
24955   bool NegA = (A.getOpcode() == ISD::FNEG);
24956   bool NegB = (B.getOpcode() == ISD::FNEG);
24957   bool NegC = (C.getOpcode() == ISD::FNEG);
24958
24959   // Negative multiplication when NegA xor NegB
24960   bool NegMul = (NegA != NegB);
24961   if (NegA)
24962     A = A.getOperand(0);
24963   if (NegB)
24964     B = B.getOperand(0);
24965   if (NegC)
24966     C = C.getOperand(0);
24967
24968   unsigned Opcode;
24969   if (!NegMul)
24970     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24971   else
24972     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24973
24974   return DAG.getNode(Opcode, dl, VT, A, B, C);
24975 }
24976
24977 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24978                                   TargetLowering::DAGCombinerInfo &DCI,
24979                                   const X86Subtarget *Subtarget) {
24980   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24981   //           (and (i32 x86isd::setcc_carry), 1)
24982   // This eliminates the zext. This transformation is necessary because
24983   // ISD::SETCC is always legalized to i8.
24984   SDLoc dl(N);
24985   SDValue N0 = N->getOperand(0);
24986   EVT VT = N->getValueType(0);
24987
24988   if (N0.getOpcode() == ISD::AND &&
24989       N0.hasOneUse() &&
24990       N0.getOperand(0).hasOneUse()) {
24991     SDValue N00 = N0.getOperand(0);
24992     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24993       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24994       if (!C || C->getZExtValue() != 1)
24995         return SDValue();
24996       return DAG.getNode(ISD::AND, dl, VT,
24997                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24998                                      N00.getOperand(0), N00.getOperand(1)),
24999                          DAG.getConstant(1, dl, VT));
25000     }
25001   }
25002
25003   if (N0.getOpcode() == ISD::TRUNCATE &&
25004       N0.hasOneUse() &&
25005       N0.getOperand(0).hasOneUse()) {
25006     SDValue N00 = N0.getOperand(0);
25007     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25008       return DAG.getNode(ISD::AND, dl, VT,
25009                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25010                                      N00.getOperand(0), N00.getOperand(1)),
25011                          DAG.getConstant(1, dl, VT));
25012     }
25013   }
25014
25015   if (VT.is256BitVector())
25016     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25017       return R;
25018
25019   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25020   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25021   // This exposes the zext to the udivrem lowering, so that it directly extends
25022   // from AH (which we otherwise need to do contortions to access).
25023   if (N0.getOpcode() == ISD::UDIVREM &&
25024       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25025       (VT == MVT::i32 || VT == MVT::i64)) {
25026     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25027     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25028                             N0.getOperand(0), N0.getOperand(1));
25029     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25030     return R.getValue(1);
25031   }
25032
25033   return SDValue();
25034 }
25035
25036 // Optimize x == -y --> x+y == 0
25037 //          x != -y --> x+y != 0
25038 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25039                                       const X86Subtarget* Subtarget) {
25040   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25041   SDValue LHS = N->getOperand(0);
25042   SDValue RHS = N->getOperand(1);
25043   EVT VT = N->getValueType(0);
25044   SDLoc DL(N);
25045
25046   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25047     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25048       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25049         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25050                                    LHS.getOperand(1));
25051         return DAG.getSetCC(DL, N->getValueType(0), addV,
25052                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25053       }
25054   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25055     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25056       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25057         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25058                                    RHS.getOperand(1));
25059         return DAG.getSetCC(DL, N->getValueType(0), addV,
25060                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25061       }
25062
25063   if (VT.getScalarType() == MVT::i1 &&
25064       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25065     bool IsSEXT0 =
25066         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25067         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25068     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25069
25070     if (!IsSEXT0 || !IsVZero1) {
25071       // Swap the operands and update the condition code.
25072       std::swap(LHS, RHS);
25073       CC = ISD::getSetCCSwappedOperands(CC);
25074
25075       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25076                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25077       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25078     }
25079
25080     if (IsSEXT0 && IsVZero1) {
25081       assert(VT == LHS.getOperand(0).getValueType() &&
25082              "Uexpected operand type");
25083       if (CC == ISD::SETGT)
25084         return DAG.getConstant(0, DL, VT);
25085       if (CC == ISD::SETLE)
25086         return DAG.getConstant(1, DL, VT);
25087       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25088         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25089
25090       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25091              "Unexpected condition code!");
25092       return LHS.getOperand(0);
25093     }
25094   }
25095
25096   return SDValue();
25097 }
25098
25099 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25100                                          SelectionDAG &DAG) {
25101   SDLoc dl(Load);
25102   MVT VT = Load->getSimpleValueType(0);
25103   MVT EVT = VT.getVectorElementType();
25104   SDValue Addr = Load->getOperand(1);
25105   SDValue NewAddr = DAG.getNode(
25106       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25107       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25108                       Addr.getSimpleValueType()));
25109
25110   SDValue NewLoad =
25111       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25112                   DAG.getMachineFunction().getMachineMemOperand(
25113                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25114   return NewLoad;
25115 }
25116
25117 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25118                                       const X86Subtarget *Subtarget) {
25119   SDLoc dl(N);
25120   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25121   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25122          "X86insertps is only defined for v4x32");
25123
25124   SDValue Ld = N->getOperand(1);
25125   if (MayFoldLoad(Ld)) {
25126     // Extract the countS bits from the immediate so we can get the proper
25127     // address when narrowing the vector load to a specific element.
25128     // When the second source op is a memory address, insertps doesn't use
25129     // countS and just gets an f32 from that address.
25130     unsigned DestIndex =
25131         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25132
25133     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25134
25135     // Create this as a scalar to vector to match the instruction pattern.
25136     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25137     // countS bits are ignored when loading from memory on insertps, which
25138     // means we don't need to explicitly set them to 0.
25139     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25140                        LoadScalarToVector, N->getOperand(2));
25141   }
25142   return SDValue();
25143 }
25144
25145 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25146   SDValue V0 = N->getOperand(0);
25147   SDValue V1 = N->getOperand(1);
25148   SDLoc DL(N);
25149   EVT VT = N->getValueType(0);
25150
25151   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25152   // operands and changing the mask to 1. This saves us a bunch of
25153   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25154   // x86InstrInfo knows how to commute this back after instruction selection
25155   // if it would help register allocation.
25156
25157   // TODO: If optimizing for size or a processor that doesn't suffer from
25158   // partial register update stalls, this should be transformed into a MOVSD
25159   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25160
25161   if (VT == MVT::v2f64)
25162     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25163       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25164         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25165         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25166       }
25167
25168   return SDValue();
25169 }
25170
25171 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25172 // as "sbb reg,reg", since it can be extended without zext and produces
25173 // an all-ones bit which is more useful than 0/1 in some cases.
25174 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25175                                MVT VT) {
25176   if (VT == MVT::i8)
25177     return DAG.getNode(ISD::AND, DL, VT,
25178                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25179                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25180                                    EFLAGS),
25181                        DAG.getConstant(1, DL, VT));
25182   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25183   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25184                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25185                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25186                                  EFLAGS));
25187 }
25188
25189 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25190 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25191                                    TargetLowering::DAGCombinerInfo &DCI,
25192                                    const X86Subtarget *Subtarget) {
25193   SDLoc DL(N);
25194   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25195   SDValue EFLAGS = N->getOperand(1);
25196
25197   if (CC == X86::COND_A) {
25198     // Try to convert COND_A into COND_B in an attempt to facilitate
25199     // materializing "setb reg".
25200     //
25201     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25202     // cannot take an immediate as its first operand.
25203     //
25204     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25205         EFLAGS.getValueType().isInteger() &&
25206         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25207       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25208                                    EFLAGS.getNode()->getVTList(),
25209                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25210       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25211       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25212     }
25213   }
25214
25215   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25216   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25217   // cases.
25218   if (CC == X86::COND_B)
25219     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25220
25221   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25222     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25223     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25224   }
25225
25226   return SDValue();
25227 }
25228
25229 // Optimize branch condition evaluation.
25230 //
25231 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25232                                     TargetLowering::DAGCombinerInfo &DCI,
25233                                     const X86Subtarget *Subtarget) {
25234   SDLoc DL(N);
25235   SDValue Chain = N->getOperand(0);
25236   SDValue Dest = N->getOperand(1);
25237   SDValue EFLAGS = N->getOperand(3);
25238   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25239
25240   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25241     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25242     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25243                        Flags);
25244   }
25245
25246   return SDValue();
25247 }
25248
25249 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25250                                                          SelectionDAG &DAG) {
25251   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25252   // optimize away operation when it's from a constant.
25253   //
25254   // The general transformation is:
25255   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25256   //       AND(VECTOR_CMP(x,y), constant2)
25257   //    constant2 = UNARYOP(constant)
25258
25259   // Early exit if this isn't a vector operation, the operand of the
25260   // unary operation isn't a bitwise AND, or if the sizes of the operations
25261   // aren't the same.
25262   EVT VT = N->getValueType(0);
25263   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25264       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25265       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25266     return SDValue();
25267
25268   // Now check that the other operand of the AND is a constant. We could
25269   // make the transformation for non-constant splats as well, but it's unclear
25270   // that would be a benefit as it would not eliminate any operations, just
25271   // perform one more step in scalar code before moving to the vector unit.
25272   if (BuildVectorSDNode *BV =
25273           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25274     // Bail out if the vector isn't a constant.
25275     if (!BV->isConstant())
25276       return SDValue();
25277
25278     // Everything checks out. Build up the new and improved node.
25279     SDLoc DL(N);
25280     EVT IntVT = BV->getValueType(0);
25281     // Create a new constant of the appropriate type for the transformed
25282     // DAG.
25283     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25284     // The AND node needs bitcasts to/from an integer vector type around it.
25285     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25286     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25287                                  N->getOperand(0)->getOperand(0), MaskConst);
25288     SDValue Res = DAG.getBitcast(VT, NewAnd);
25289     return Res;
25290   }
25291
25292   return SDValue();
25293 }
25294
25295 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25296                                         const X86Subtarget *Subtarget) {
25297   SDValue Op0 = N->getOperand(0);
25298   EVT VT = N->getValueType(0);
25299   EVT InVT = Op0.getValueType();
25300   EVT InSVT = InVT.getScalarType();
25301   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25302
25303   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25304   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25305   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25306     SDLoc dl(N);
25307     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25308                                  InVT.getVectorNumElements());
25309     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25310
25311     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25312       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25313
25314     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25315   }
25316
25317   return SDValue();
25318 }
25319
25320 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25321                                         const X86Subtarget *Subtarget) {
25322   // First try to optimize away the conversion entirely when it's
25323   // conditionally from a constant. Vectors only.
25324   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25325     return Res;
25326
25327   // Now move on to more general possibilities.
25328   SDValue Op0 = N->getOperand(0);
25329   EVT VT = N->getValueType(0);
25330   EVT InVT = Op0.getValueType();
25331   EVT InSVT = InVT.getScalarType();
25332
25333   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25334   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25335   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25336     SDLoc dl(N);
25337     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25338                                  InVT.getVectorNumElements());
25339     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25340     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25341   }
25342
25343   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25344   // a 32-bit target where SSE doesn't support i64->FP operations.
25345   if (Op0.getOpcode() == ISD::LOAD) {
25346     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25347     EVT LdVT = Ld->getValueType(0);
25348
25349     // This transformation is not supported if the result type is f16
25350     if (VT == MVT::f16)
25351       return SDValue();
25352
25353     if (!Ld->isVolatile() && !VT.isVector() &&
25354         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25355         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25356       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25357           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25358       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25359       return FILDChain;
25360     }
25361   }
25362   return SDValue();
25363 }
25364
25365 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25366 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25367                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25368   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25369   // the result is either zero or one (depending on the input carry bit).
25370   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25371   if (X86::isZeroNode(N->getOperand(0)) &&
25372       X86::isZeroNode(N->getOperand(1)) &&
25373       // We don't have a good way to replace an EFLAGS use, so only do this when
25374       // dead right now.
25375       SDValue(N, 1).use_empty()) {
25376     SDLoc DL(N);
25377     EVT VT = N->getValueType(0);
25378     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25379     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25380                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25381                                            DAG.getConstant(X86::COND_B, DL,
25382                                                            MVT::i8),
25383                                            N->getOperand(2)),
25384                                DAG.getConstant(1, DL, VT));
25385     return DCI.CombineTo(N, Res1, CarryOut);
25386   }
25387
25388   return SDValue();
25389 }
25390
25391 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25392 //      (add Y, (setne X, 0)) -> sbb -1, Y
25393 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25394 //      (sub (setne X, 0), Y) -> adc -1, Y
25395 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25396   SDLoc DL(N);
25397
25398   // Look through ZExts.
25399   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25400   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25401     return SDValue();
25402
25403   SDValue SetCC = Ext.getOperand(0);
25404   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25405     return SDValue();
25406
25407   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25408   if (CC != X86::COND_E && CC != X86::COND_NE)
25409     return SDValue();
25410
25411   SDValue Cmp = SetCC.getOperand(1);
25412   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25413       !X86::isZeroNode(Cmp.getOperand(1)) ||
25414       !Cmp.getOperand(0).getValueType().isInteger())
25415     return SDValue();
25416
25417   SDValue CmpOp0 = Cmp.getOperand(0);
25418   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25419                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25420
25421   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25422   if (CC == X86::COND_NE)
25423     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25424                        DL, OtherVal.getValueType(), OtherVal,
25425                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25426                        NewCmp);
25427   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25428                      DL, OtherVal.getValueType(), OtherVal,
25429                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25430 }
25431
25432 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25433 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25434                                  const X86Subtarget *Subtarget) {
25435   EVT VT = N->getValueType(0);
25436   SDValue Op0 = N->getOperand(0);
25437   SDValue Op1 = N->getOperand(1);
25438
25439   // Try to synthesize horizontal adds from adds of shuffles.
25440   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25441        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25442       isHorizontalBinOp(Op0, Op1, true))
25443     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25444
25445   return OptimizeConditionalInDecrement(N, DAG);
25446 }
25447
25448 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25449                                  const X86Subtarget *Subtarget) {
25450   SDValue Op0 = N->getOperand(0);
25451   SDValue Op1 = N->getOperand(1);
25452
25453   // X86 can't encode an immediate LHS of a sub. See if we can push the
25454   // negation into a preceding instruction.
25455   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25456     // If the RHS of the sub is a XOR with one use and a constant, invert the
25457     // immediate. Then add one to the LHS of the sub so we can turn
25458     // X-Y -> X+~Y+1, saving one register.
25459     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25460         isa<ConstantSDNode>(Op1.getOperand(1))) {
25461       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25462       EVT VT = Op0.getValueType();
25463       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25464                                    Op1.getOperand(0),
25465                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25466       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25467                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25468     }
25469   }
25470
25471   // Try to synthesize horizontal adds from adds of shuffles.
25472   EVT VT = N->getValueType(0);
25473   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25474        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25475       isHorizontalBinOp(Op0, Op1, true))
25476     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25477
25478   return OptimizeConditionalInDecrement(N, DAG);
25479 }
25480
25481 /// performVZEXTCombine - Performs build vector combines
25482 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25483                                    TargetLowering::DAGCombinerInfo &DCI,
25484                                    const X86Subtarget *Subtarget) {
25485   SDLoc DL(N);
25486   MVT VT = N->getSimpleValueType(0);
25487   SDValue Op = N->getOperand(0);
25488   MVT OpVT = Op.getSimpleValueType();
25489   MVT OpEltVT = OpVT.getVectorElementType();
25490   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25491
25492   // (vzext (bitcast (vzext (x)) -> (vzext x)
25493   SDValue V = Op;
25494   while (V.getOpcode() == ISD::BITCAST)
25495     V = V.getOperand(0);
25496
25497   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25498     MVT InnerVT = V.getSimpleValueType();
25499     MVT InnerEltVT = InnerVT.getVectorElementType();
25500
25501     // If the element sizes match exactly, we can just do one larger vzext. This
25502     // is always an exact type match as vzext operates on integer types.
25503     if (OpEltVT == InnerEltVT) {
25504       assert(OpVT == InnerVT && "Types must match for vzext!");
25505       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25506     }
25507
25508     // The only other way we can combine them is if only a single element of the
25509     // inner vzext is used in the input to the outer vzext.
25510     if (InnerEltVT.getSizeInBits() < InputBits)
25511       return SDValue();
25512
25513     // In this case, the inner vzext is completely dead because we're going to
25514     // only look at bits inside of the low element. Just do the outer vzext on
25515     // a bitcast of the input to the inner.
25516     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25517   }
25518
25519   // Check if we can bypass extracting and re-inserting an element of an input
25520   // vector. Essentially:
25521   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25522   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25523       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25524       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25525     SDValue ExtractedV = V.getOperand(0);
25526     SDValue OrigV = ExtractedV.getOperand(0);
25527     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25528       if (ExtractIdx->getZExtValue() == 0) {
25529         MVT OrigVT = OrigV.getSimpleValueType();
25530         // Extract a subvector if necessary...
25531         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25532           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25533           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25534                                     OrigVT.getVectorNumElements() / Ratio);
25535           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25536                               DAG.getIntPtrConstant(0, DL));
25537         }
25538         Op = DAG.getBitcast(OpVT, OrigV);
25539         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25540       }
25541   }
25542
25543   return SDValue();
25544 }
25545
25546 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25547                                              DAGCombinerInfo &DCI) const {
25548   SelectionDAG &DAG = DCI.DAG;
25549   switch (N->getOpcode()) {
25550   default: break;
25551   case ISD::EXTRACT_VECTOR_ELT:
25552     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25553   case ISD::VSELECT:
25554   case ISD::SELECT:
25555   case X86ISD::SHRUNKBLEND:
25556     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25557   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25558   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25559   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25560   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25561   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25562   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25563   case ISD::SHL:
25564   case ISD::SRA:
25565   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25566   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25567   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25568   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25569   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25570   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25571   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25572   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25573   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25574   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25575   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25576   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25577   case X86ISD::FXOR:
25578   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25579   case X86ISD::FMIN:
25580   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25581   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25582   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25583   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25584   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25585   case ISD::ANY_EXTEND:
25586   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25587   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25588   case ISD::SIGN_EXTEND_INREG:
25589     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25590   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25591   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25592   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25593   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25594   case X86ISD::SHUFP:       // Handle all target specific shuffles
25595   case X86ISD::PALIGNR:
25596   case X86ISD::UNPCKH:
25597   case X86ISD::UNPCKL:
25598   case X86ISD::MOVHLPS:
25599   case X86ISD::MOVLHPS:
25600   case X86ISD::PSHUFB:
25601   case X86ISD::PSHUFD:
25602   case X86ISD::PSHUFHW:
25603   case X86ISD::PSHUFLW:
25604   case X86ISD::MOVSS:
25605   case X86ISD::MOVSD:
25606   case X86ISD::VPERMILPI:
25607   case X86ISD::VPERM2X128:
25608   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25609   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25610   case X86ISD::INSERTPS: {
25611     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25612       return PerformINSERTPSCombine(N, DAG, Subtarget);
25613     break;
25614   }
25615   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25616   }
25617
25618   return SDValue();
25619 }
25620
25621 /// isTypeDesirableForOp - Return true if the target has native support for
25622 /// the specified value type and it is 'desirable' to use the type for the
25623 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25624 /// instruction encodings are longer and some i16 instructions are slow.
25625 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25626   if (!isTypeLegal(VT))
25627     return false;
25628   if (VT != MVT::i16)
25629     return true;
25630
25631   switch (Opc) {
25632   default:
25633     return true;
25634   case ISD::LOAD:
25635   case ISD::SIGN_EXTEND:
25636   case ISD::ZERO_EXTEND:
25637   case ISD::ANY_EXTEND:
25638   case ISD::SHL:
25639   case ISD::SRL:
25640   case ISD::SUB:
25641   case ISD::ADD:
25642   case ISD::MUL:
25643   case ISD::AND:
25644   case ISD::OR:
25645   case ISD::XOR:
25646     return false;
25647   }
25648 }
25649
25650 /// IsDesirableToPromoteOp - This method query the target whether it is
25651 /// beneficial for dag combiner to promote the specified node. If true, it
25652 /// should return the desired promotion type by reference.
25653 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25654   EVT VT = Op.getValueType();
25655   if (VT != MVT::i16)
25656     return false;
25657
25658   bool Promote = false;
25659   bool Commute = false;
25660   switch (Op.getOpcode()) {
25661   default: break;
25662   case ISD::LOAD: {
25663     LoadSDNode *LD = cast<LoadSDNode>(Op);
25664     // If the non-extending load has a single use and it's not live out, then it
25665     // might be folded.
25666     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25667                                                      Op.hasOneUse()*/) {
25668       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25669              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25670         // The only case where we'd want to promote LOAD (rather then it being
25671         // promoted as an operand is when it's only use is liveout.
25672         if (UI->getOpcode() != ISD::CopyToReg)
25673           return false;
25674       }
25675     }
25676     Promote = true;
25677     break;
25678   }
25679   case ISD::SIGN_EXTEND:
25680   case ISD::ZERO_EXTEND:
25681   case ISD::ANY_EXTEND:
25682     Promote = true;
25683     break;
25684   case ISD::SHL:
25685   case ISD::SRL: {
25686     SDValue N0 = Op.getOperand(0);
25687     // Look out for (store (shl (load), x)).
25688     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25689       return false;
25690     Promote = true;
25691     break;
25692   }
25693   case ISD::ADD:
25694   case ISD::MUL:
25695   case ISD::AND:
25696   case ISD::OR:
25697   case ISD::XOR:
25698     Commute = true;
25699     // fallthrough
25700   case ISD::SUB: {
25701     SDValue N0 = Op.getOperand(0);
25702     SDValue N1 = Op.getOperand(1);
25703     if (!Commute && MayFoldLoad(N1))
25704       return false;
25705     // Avoid disabling potential load folding opportunities.
25706     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25707       return false;
25708     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25709       return false;
25710     Promote = true;
25711   }
25712   }
25713
25714   PVT = MVT::i32;
25715   return Promote;
25716 }
25717
25718 //===----------------------------------------------------------------------===//
25719 //                           X86 Inline Assembly Support
25720 //===----------------------------------------------------------------------===//
25721
25722 // Helper to match a string separated by whitespace.
25723 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25724   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25725
25726   for (StringRef Piece : Pieces) {
25727     if (!S.startswith(Piece)) // Check if the piece matches.
25728       return false;
25729
25730     S = S.substr(Piece.size());
25731     StringRef::size_type Pos = S.find_first_not_of(" \t");
25732     if (Pos == 0) // We matched a prefix.
25733       return false;
25734
25735     S = S.substr(Pos);
25736   }
25737
25738   return S.empty();
25739 }
25740
25741 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25742
25743   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25744     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25745         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25746         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25747
25748       if (AsmPieces.size() == 3)
25749         return true;
25750       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25751         return true;
25752     }
25753   }
25754   return false;
25755 }
25756
25757 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25758   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25759
25760   std::string AsmStr = IA->getAsmString();
25761
25762   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25763   if (!Ty || Ty->getBitWidth() % 16 != 0)
25764     return false;
25765
25766   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25767   SmallVector<StringRef, 4> AsmPieces;
25768   SplitString(AsmStr, AsmPieces, ";\n");
25769
25770   switch (AsmPieces.size()) {
25771   default: return false;
25772   case 1:
25773     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25774     // we will turn this bswap into something that will be lowered to logical
25775     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25776     // lower so don't worry about this.
25777     // bswap $0
25778     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25779         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25780         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25781         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25782         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25783         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25784       // No need to check constraints, nothing other than the equivalent of
25785       // "=r,0" would be valid here.
25786       return IntrinsicLowering::LowerToByteSwap(CI);
25787     }
25788
25789     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25790     if (CI->getType()->isIntegerTy(16) &&
25791         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25792         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25793          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25794       AsmPieces.clear();
25795       StringRef ConstraintsStr = IA->getConstraintString();
25796       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25797       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25798       if (clobbersFlagRegisters(AsmPieces))
25799         return IntrinsicLowering::LowerToByteSwap(CI);
25800     }
25801     break;
25802   case 3:
25803     if (CI->getType()->isIntegerTy(32) &&
25804         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25805         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25806         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25807         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25808       AsmPieces.clear();
25809       StringRef ConstraintsStr = IA->getConstraintString();
25810       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25811       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25812       if (clobbersFlagRegisters(AsmPieces))
25813         return IntrinsicLowering::LowerToByteSwap(CI);
25814     }
25815
25816     if (CI->getType()->isIntegerTy(64)) {
25817       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25818       if (Constraints.size() >= 2 &&
25819           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25820           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25821         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25822         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25823             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25824             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25825           return IntrinsicLowering::LowerToByteSwap(CI);
25826       }
25827     }
25828     break;
25829   }
25830   return false;
25831 }
25832
25833 /// getConstraintType - Given a constraint letter, return the type of
25834 /// constraint it is for this target.
25835 X86TargetLowering::ConstraintType
25836 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25837   if (Constraint.size() == 1) {
25838     switch (Constraint[0]) {
25839     case 'R':
25840     case 'q':
25841     case 'Q':
25842     case 'f':
25843     case 't':
25844     case 'u':
25845     case 'y':
25846     case 'x':
25847     case 'Y':
25848     case 'l':
25849       return C_RegisterClass;
25850     case 'a':
25851     case 'b':
25852     case 'c':
25853     case 'd':
25854     case 'S':
25855     case 'D':
25856     case 'A':
25857       return C_Register;
25858     case 'I':
25859     case 'J':
25860     case 'K':
25861     case 'L':
25862     case 'M':
25863     case 'N':
25864     case 'G':
25865     case 'C':
25866     case 'e':
25867     case 'Z':
25868       return C_Other;
25869     default:
25870       break;
25871     }
25872   }
25873   return TargetLowering::getConstraintType(Constraint);
25874 }
25875
25876 /// Examine constraint type and operand type and determine a weight value.
25877 /// This object must already have been set up with the operand type
25878 /// and the current alternative constraint selected.
25879 TargetLowering::ConstraintWeight
25880   X86TargetLowering::getSingleConstraintMatchWeight(
25881     AsmOperandInfo &info, const char *constraint) const {
25882   ConstraintWeight weight = CW_Invalid;
25883   Value *CallOperandVal = info.CallOperandVal;
25884     // If we don't have a value, we can't do a match,
25885     // but allow it at the lowest weight.
25886   if (!CallOperandVal)
25887     return CW_Default;
25888   Type *type = CallOperandVal->getType();
25889   // Look at the constraint type.
25890   switch (*constraint) {
25891   default:
25892     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25893   case 'R':
25894   case 'q':
25895   case 'Q':
25896   case 'a':
25897   case 'b':
25898   case 'c':
25899   case 'd':
25900   case 'S':
25901   case 'D':
25902   case 'A':
25903     if (CallOperandVal->getType()->isIntegerTy())
25904       weight = CW_SpecificReg;
25905     break;
25906   case 'f':
25907   case 't':
25908   case 'u':
25909     if (type->isFloatingPointTy())
25910       weight = CW_SpecificReg;
25911     break;
25912   case 'y':
25913     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25914       weight = CW_SpecificReg;
25915     break;
25916   case 'x':
25917   case 'Y':
25918     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25919         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25920       weight = CW_Register;
25921     break;
25922   case 'I':
25923     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25924       if (C->getZExtValue() <= 31)
25925         weight = CW_Constant;
25926     }
25927     break;
25928   case 'J':
25929     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25930       if (C->getZExtValue() <= 63)
25931         weight = CW_Constant;
25932     }
25933     break;
25934   case 'K':
25935     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25936       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25937         weight = CW_Constant;
25938     }
25939     break;
25940   case 'L':
25941     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25942       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25943         weight = CW_Constant;
25944     }
25945     break;
25946   case 'M':
25947     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25948       if (C->getZExtValue() <= 3)
25949         weight = CW_Constant;
25950     }
25951     break;
25952   case 'N':
25953     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25954       if (C->getZExtValue() <= 0xff)
25955         weight = CW_Constant;
25956     }
25957     break;
25958   case 'G':
25959   case 'C':
25960     if (isa<ConstantFP>(CallOperandVal)) {
25961       weight = CW_Constant;
25962     }
25963     break;
25964   case 'e':
25965     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25966       if ((C->getSExtValue() >= -0x80000000LL) &&
25967           (C->getSExtValue() <= 0x7fffffffLL))
25968         weight = CW_Constant;
25969     }
25970     break;
25971   case 'Z':
25972     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25973       if (C->getZExtValue() <= 0xffffffff)
25974         weight = CW_Constant;
25975     }
25976     break;
25977   }
25978   return weight;
25979 }
25980
25981 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25982 /// with another that has more specific requirements based on the type of the
25983 /// corresponding operand.
25984 const char *X86TargetLowering::
25985 LowerXConstraint(EVT ConstraintVT) const {
25986   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25987   // 'f' like normal targets.
25988   if (ConstraintVT.isFloatingPoint()) {
25989     if (Subtarget->hasSSE2())
25990       return "Y";
25991     if (Subtarget->hasSSE1())
25992       return "x";
25993   }
25994
25995   return TargetLowering::LowerXConstraint(ConstraintVT);
25996 }
25997
25998 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25999 /// vector.  If it is invalid, don't add anything to Ops.
26000 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26001                                                      std::string &Constraint,
26002                                                      std::vector<SDValue>&Ops,
26003                                                      SelectionDAG &DAG) const {
26004   SDValue Result;
26005
26006   // Only support length 1 constraints for now.
26007   if (Constraint.length() > 1) return;
26008
26009   char ConstraintLetter = Constraint[0];
26010   switch (ConstraintLetter) {
26011   default: break;
26012   case 'I':
26013     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26014       if (C->getZExtValue() <= 31) {
26015         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26016                                        Op.getValueType());
26017         break;
26018       }
26019     }
26020     return;
26021   case 'J':
26022     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26023       if (C->getZExtValue() <= 63) {
26024         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26025                                        Op.getValueType());
26026         break;
26027       }
26028     }
26029     return;
26030   case 'K':
26031     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26032       if (isInt<8>(C->getSExtValue())) {
26033         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26034                                        Op.getValueType());
26035         break;
26036       }
26037     }
26038     return;
26039   case 'L':
26040     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26041       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26042           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26043         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26044                                        Op.getValueType());
26045         break;
26046       }
26047     }
26048     return;
26049   case 'M':
26050     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26051       if (C->getZExtValue() <= 3) {
26052         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26053                                        Op.getValueType());
26054         break;
26055       }
26056     }
26057     return;
26058   case 'N':
26059     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26060       if (C->getZExtValue() <= 255) {
26061         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26062                                        Op.getValueType());
26063         break;
26064       }
26065     }
26066     return;
26067   case 'O':
26068     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26069       if (C->getZExtValue() <= 127) {
26070         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26071                                        Op.getValueType());
26072         break;
26073       }
26074     }
26075     return;
26076   case 'e': {
26077     // 32-bit signed value
26078     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26079       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26080                                            C->getSExtValue())) {
26081         // Widen to 64 bits here to get it sign extended.
26082         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26083         break;
26084       }
26085     // FIXME gcc accepts some relocatable values here too, but only in certain
26086     // memory models; it's complicated.
26087     }
26088     return;
26089   }
26090   case 'Z': {
26091     // 32-bit unsigned value
26092     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26093       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26094                                            C->getZExtValue())) {
26095         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26096                                        Op.getValueType());
26097         break;
26098       }
26099     }
26100     // FIXME gcc accepts some relocatable values here too, but only in certain
26101     // memory models; it's complicated.
26102     return;
26103   }
26104   case 'i': {
26105     // Literal immediates are always ok.
26106     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26107       // Widen to 64 bits here to get it sign extended.
26108       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26109       break;
26110     }
26111
26112     // In any sort of PIC mode addresses need to be computed at runtime by
26113     // adding in a register or some sort of table lookup.  These can't
26114     // be used as immediates.
26115     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26116       return;
26117
26118     // If we are in non-pic codegen mode, we allow the address of a global (with
26119     // an optional displacement) to be used with 'i'.
26120     GlobalAddressSDNode *GA = nullptr;
26121     int64_t Offset = 0;
26122
26123     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26124     while (1) {
26125       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26126         Offset += GA->getOffset();
26127         break;
26128       } else if (Op.getOpcode() == ISD::ADD) {
26129         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26130           Offset += C->getZExtValue();
26131           Op = Op.getOperand(0);
26132           continue;
26133         }
26134       } else if (Op.getOpcode() == ISD::SUB) {
26135         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26136           Offset += -C->getZExtValue();
26137           Op = Op.getOperand(0);
26138           continue;
26139         }
26140       }
26141
26142       // Otherwise, this isn't something we can handle, reject it.
26143       return;
26144     }
26145
26146     const GlobalValue *GV = GA->getGlobal();
26147     // If we require an extra load to get this address, as in PIC mode, we
26148     // can't accept it.
26149     if (isGlobalStubReference(
26150             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26151       return;
26152
26153     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26154                                         GA->getValueType(0), Offset);
26155     break;
26156   }
26157   }
26158
26159   if (Result.getNode()) {
26160     Ops.push_back(Result);
26161     return;
26162   }
26163   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26164 }
26165
26166 std::pair<unsigned, const TargetRegisterClass *>
26167 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26168                                                 StringRef Constraint,
26169                                                 MVT VT) const {
26170   // First, see if this is a constraint that directly corresponds to an LLVM
26171   // register class.
26172   if (Constraint.size() == 1) {
26173     // GCC Constraint Letters
26174     switch (Constraint[0]) {
26175     default: break;
26176       // TODO: Slight differences here in allocation order and leaving
26177       // RIP in the class. Do they matter any more here than they do
26178       // in the normal allocation?
26179     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26180       if (Subtarget->is64Bit()) {
26181         if (VT == MVT::i32 || VT == MVT::f32)
26182           return std::make_pair(0U, &X86::GR32RegClass);
26183         if (VT == MVT::i16)
26184           return std::make_pair(0U, &X86::GR16RegClass);
26185         if (VT == MVT::i8 || VT == MVT::i1)
26186           return std::make_pair(0U, &X86::GR8RegClass);
26187         if (VT == MVT::i64 || VT == MVT::f64)
26188           return std::make_pair(0U, &X86::GR64RegClass);
26189         break;
26190       }
26191       // 32-bit fallthrough
26192     case 'Q':   // Q_REGS
26193       if (VT == MVT::i32 || VT == MVT::f32)
26194         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26195       if (VT == MVT::i16)
26196         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26197       if (VT == MVT::i8 || VT == MVT::i1)
26198         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26199       if (VT == MVT::i64)
26200         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26201       break;
26202     case 'r':   // GENERAL_REGS
26203     case 'l':   // INDEX_REGS
26204       if (VT == MVT::i8 || VT == MVT::i1)
26205         return std::make_pair(0U, &X86::GR8RegClass);
26206       if (VT == MVT::i16)
26207         return std::make_pair(0U, &X86::GR16RegClass);
26208       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26209         return std::make_pair(0U, &X86::GR32RegClass);
26210       return std::make_pair(0U, &X86::GR64RegClass);
26211     case 'R':   // LEGACY_REGS
26212       if (VT == MVT::i8 || VT == MVT::i1)
26213         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26214       if (VT == MVT::i16)
26215         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26216       if (VT == MVT::i32 || !Subtarget->is64Bit())
26217         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26218       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26219     case 'f':  // FP Stack registers.
26220       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26221       // value to the correct fpstack register class.
26222       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26223         return std::make_pair(0U, &X86::RFP32RegClass);
26224       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26225         return std::make_pair(0U, &X86::RFP64RegClass);
26226       return std::make_pair(0U, &X86::RFP80RegClass);
26227     case 'y':   // MMX_REGS if MMX allowed.
26228       if (!Subtarget->hasMMX()) break;
26229       return std::make_pair(0U, &X86::VR64RegClass);
26230     case 'Y':   // SSE_REGS if SSE2 allowed
26231       if (!Subtarget->hasSSE2()) break;
26232       // FALL THROUGH.
26233     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26234       if (!Subtarget->hasSSE1()) break;
26235
26236       switch (VT.SimpleTy) {
26237       default: break;
26238       // Scalar SSE types.
26239       case MVT::f32:
26240       case MVT::i32:
26241         return std::make_pair(0U, &X86::FR32RegClass);
26242       case MVT::f64:
26243       case MVT::i64:
26244         return std::make_pair(0U, &X86::FR64RegClass);
26245       // Vector types.
26246       case MVT::v16i8:
26247       case MVT::v8i16:
26248       case MVT::v4i32:
26249       case MVT::v2i64:
26250       case MVT::v4f32:
26251       case MVT::v2f64:
26252         return std::make_pair(0U, &X86::VR128RegClass);
26253       // AVX types.
26254       case MVT::v32i8:
26255       case MVT::v16i16:
26256       case MVT::v8i32:
26257       case MVT::v4i64:
26258       case MVT::v8f32:
26259       case MVT::v4f64:
26260         return std::make_pair(0U, &X86::VR256RegClass);
26261       case MVT::v8f64:
26262       case MVT::v16f32:
26263       case MVT::v16i32:
26264       case MVT::v8i64:
26265         return std::make_pair(0U, &X86::VR512RegClass);
26266       }
26267       break;
26268     }
26269   }
26270
26271   // Use the default implementation in TargetLowering to convert the register
26272   // constraint into a member of a register class.
26273   std::pair<unsigned, const TargetRegisterClass*> Res;
26274   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26275
26276   // Not found as a standard register?
26277   if (!Res.second) {
26278     // Map st(0) -> st(7) -> ST0
26279     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26280         tolower(Constraint[1]) == 's' &&
26281         tolower(Constraint[2]) == 't' &&
26282         Constraint[3] == '(' &&
26283         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26284         Constraint[5] == ')' &&
26285         Constraint[6] == '}') {
26286
26287       Res.first = X86::FP0+Constraint[4]-'0';
26288       Res.second = &X86::RFP80RegClass;
26289       return Res;
26290     }
26291
26292     // GCC allows "st(0)" to be called just plain "st".
26293     if (StringRef("{st}").equals_lower(Constraint)) {
26294       Res.first = X86::FP0;
26295       Res.second = &X86::RFP80RegClass;
26296       return Res;
26297     }
26298
26299     // flags -> EFLAGS
26300     if (StringRef("{flags}").equals_lower(Constraint)) {
26301       Res.first = X86::EFLAGS;
26302       Res.second = &X86::CCRRegClass;
26303       return Res;
26304     }
26305
26306     // 'A' means EAX + EDX.
26307     if (Constraint == "A") {
26308       Res.first = X86::EAX;
26309       Res.second = &X86::GR32_ADRegClass;
26310       return Res;
26311     }
26312     return Res;
26313   }
26314
26315   // Otherwise, check to see if this is a register class of the wrong value
26316   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26317   // turn into {ax},{dx}.
26318   // MVT::Other is used to specify clobber names.
26319   if (Res.second->hasType(VT) || VT == MVT::Other)
26320     return Res;   // Correct type already, nothing to do.
26321
26322   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26323   // return "eax". This should even work for things like getting 64bit integer
26324   // registers when given an f64 type.
26325   const TargetRegisterClass *Class = Res.second;
26326   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26327       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26328     unsigned Size = VT.getSizeInBits();
26329     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26330                                   : Size == 16 ? MVT::i16
26331                                   : Size == 32 ? MVT::i32
26332                                   : Size == 64 ? MVT::i64
26333                                   : MVT::Other;
26334     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26335     if (DestReg > 0) {
26336       Res.first = DestReg;
26337       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26338                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26339                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26340                  : &X86::GR64RegClass;
26341       assert(Res.second->contains(Res.first) && "Register in register class");
26342     } else {
26343       // No register found/type mismatch.
26344       Res.first = 0;
26345       Res.second = nullptr;
26346     }
26347   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26348              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26349              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26350              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26351              Class == &X86::VR512RegClass) {
26352     // Handle references to XMM physical registers that got mapped into the
26353     // wrong class.  This can happen with constraints like {xmm0} where the
26354     // target independent register mapper will just pick the first match it can
26355     // find, ignoring the required type.
26356
26357     if (VT == MVT::f32 || VT == MVT::i32)
26358       Res.second = &X86::FR32RegClass;
26359     else if (VT == MVT::f64 || VT == MVT::i64)
26360       Res.second = &X86::FR64RegClass;
26361     else if (X86::VR128RegClass.hasType(VT))
26362       Res.second = &X86::VR128RegClass;
26363     else if (X86::VR256RegClass.hasType(VT))
26364       Res.second = &X86::VR256RegClass;
26365     else if (X86::VR512RegClass.hasType(VT))
26366       Res.second = &X86::VR512RegClass;
26367     else {
26368       // Type mismatch and not a clobber: Return an error;
26369       Res.first = 0;
26370       Res.second = nullptr;
26371     }
26372   }
26373
26374   return Res;
26375 }
26376
26377 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26378                                             const AddrMode &AM, Type *Ty,
26379                                             unsigned AS) const {
26380   // Scaling factors are not free at all.
26381   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26382   // will take 2 allocations in the out of order engine instead of 1
26383   // for plain addressing mode, i.e. inst (reg1).
26384   // E.g.,
26385   // vaddps (%rsi,%drx), %ymm0, %ymm1
26386   // Requires two allocations (one for the load, one for the computation)
26387   // whereas:
26388   // vaddps (%rsi), %ymm0, %ymm1
26389   // Requires just 1 allocation, i.e., freeing allocations for other operations
26390   // and having less micro operations to execute.
26391   //
26392   // For some X86 architectures, this is even worse because for instance for
26393   // stores, the complex addressing mode forces the instruction to use the
26394   // "load" ports instead of the dedicated "store" port.
26395   // E.g., on Haswell:
26396   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26397   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26398   if (isLegalAddressingMode(DL, AM, Ty, AS))
26399     // Scale represents reg2 * scale, thus account for 1
26400     // as soon as we use a second register.
26401     return AM.Scale != 0;
26402   return -1;
26403 }
26404
26405 bool X86TargetLowering::isTargetFTOL() const {
26406   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26407 }