6dd4fb8d98eec40dc3e52eb6070b6b6f110f76de
[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
1203     // In the customized shift lowering, the legal cases in AVX2 will be
1204     // recognized.
1205     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1206     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1207
1208     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1209     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1210
1211     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1212     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1213
1214     // Custom lower several nodes for 256-bit types.
1215     for (MVT VT : MVT::vector_valuetypes()) {
1216       if (VT.getScalarSizeInBits() >= 32) {
1217         setOperationAction(ISD::MLOAD,  VT, Legal);
1218         setOperationAction(ISD::MSTORE, VT, Legal);
1219       }
1220       // Extract subvector is special because the value type
1221       // (result) is 128-bit but the source is 256-bit wide.
1222       if (VT.is128BitVector()) {
1223         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1224       }
1225       // Do not attempt to custom lower other non-256-bit vectors
1226       if (!VT.is256BitVector())
1227         continue;
1228
1229       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1230       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1231       setOperationAction(ISD::VSELECT,            VT, Custom);
1232       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1233       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1234       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1235       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1236       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1237     }
1238
1239     if (Subtarget->hasInt256())
1240       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1241
1242
1243     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1244     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1245       MVT VT = (MVT::SimpleValueType)i;
1246
1247       // Do not attempt to promote non-256-bit vectors
1248       if (!VT.is256BitVector())
1249         continue;
1250
1251       setOperationAction(ISD::AND,    VT, Promote);
1252       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1253       setOperationAction(ISD::OR,     VT, Promote);
1254       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1255       setOperationAction(ISD::XOR,    VT, Promote);
1256       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1257       setOperationAction(ISD::LOAD,   VT, Promote);
1258       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1259       setOperationAction(ISD::SELECT, VT, Promote);
1260       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1261     }
1262   }
1263
1264   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1265     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1266     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1267     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1268     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1269
1270     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1271     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1272     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1273
1274     for (MVT VT : MVT::fp_vector_valuetypes())
1275       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1276
1277     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1278     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1279     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1280     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1289
1290     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1291     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1292     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1293     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1294     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1295     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1296     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1297     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1298     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1299     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1300     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1301     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1302     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1303
1304     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1305     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1306     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1307     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1308     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1309     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1310
1311     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1312     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1313     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1314     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1315     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1316     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1317     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1318     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1319
1320     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1321     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1322     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1323     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1324     if (Subtarget->is64Bit()) {
1325       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1326       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1327       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1328       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1329     }
1330     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1331     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1332     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1333     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1334     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1336     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1337     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1339     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1340     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1341     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1342     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1344     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1345     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1346
1347     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1348     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1349     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1350     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1351     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1352     if (Subtarget->hasVLX()){
1353       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1354       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1355       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1356       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1357       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1358
1359       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1360       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1361       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1362       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1363       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1364     }
1365     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1366     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1368     if (Subtarget->hasDQI()) {
1369       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1370       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1371
1372       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1373       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1374       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1375       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1376       if (Subtarget->hasVLX()) {
1377         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1378         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1379         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1380         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1381         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1382         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1383         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1384         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1385       }
1386     }
1387     if (Subtarget->hasVLX()) {
1388       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1389       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1390       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1391       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1392       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1393       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1394       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1395       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1396     }
1397     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1398     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1399     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1400     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1401     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1402     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1403     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1404     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1405     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1406     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1407     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1408     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1409     if (Subtarget->hasDQI()) {
1410       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1411       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1412     }
1413     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1414     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1415     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1416     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1417     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1418     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1419     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1420     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1421     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1422     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1423
1424     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1425     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1426     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1427     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1428     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1429
1430     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1431     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1432
1433     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1434
1435     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1436     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1437     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1438     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1439     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1440     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1441     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1442     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1443     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1444     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1445     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1446
1447     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1448     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1449     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1450     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1451     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1452     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1453     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1454     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1455
1456     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1457     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1458
1459     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1461
1462     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1465     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1466
1467     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1468     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1469
1470     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1474     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1475     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1476     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1477     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1478     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1479
1480     if (Subtarget->hasCDI()) {
1481       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1482       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1483     }
1484     if (Subtarget->hasDQI()) {
1485       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1486       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1487       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1488     }
1489     // Custom lower several nodes.
1490     for (MVT VT : MVT::vector_valuetypes()) {
1491       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1492       if (EltSize == 1) {
1493         setOperationAction(ISD::AND, VT, Legal);
1494         setOperationAction(ISD::OR,  VT, Legal);
1495         setOperationAction(ISD::XOR,  VT, Legal);
1496       }
1497       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1498         setOperationAction(ISD::MGATHER,  VT, Custom);
1499         setOperationAction(ISD::MSCATTER, VT, Custom);
1500       }
1501       // Extract subvector is special because the value type
1502       // (result) is 256/128-bit but the source is 512-bit wide.
1503       if (VT.is128BitVector() || VT.is256BitVector()) {
1504         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1505       }
1506       if (VT.getVectorElementType() == MVT::i1)
1507         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1508
1509       // Do not attempt to custom lower other non-512-bit vectors
1510       if (!VT.is512BitVector())
1511         continue;
1512
1513       if (EltSize >= 32) {
1514         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1515         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1516         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1517         setOperationAction(ISD::VSELECT,             VT, Legal);
1518         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1519         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1520         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1521         setOperationAction(ISD::MLOAD,               VT, Legal);
1522         setOperationAction(ISD::MSTORE,              VT, Legal);
1523       }
1524     }
1525     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1526       MVT VT = (MVT::SimpleValueType)i;
1527
1528       // Do not attempt to promote non-512-bit vectors.
1529       if (!VT.is512BitVector())
1530         continue;
1531
1532       setOperationAction(ISD::SELECT, VT, Promote);
1533       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1534     }
1535   }// has  AVX-512
1536
1537   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1538     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1539     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1540
1541     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1542     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1543
1544     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1545     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1546     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1547     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1548     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1549     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1550     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1551     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1552     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1553     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1554     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1555     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1556     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1557     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1558     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1559     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1560     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1561     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1562     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1563     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1564     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1565     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1566     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1567     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1568     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1569     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1570     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1571     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1572     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1573     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1574
1575     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1576     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1577     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1578     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1579     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1580     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1581     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1582     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1583
1584     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1585     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1586     if (Subtarget->hasVLX())
1587       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1588
1589     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1590       const MVT VT = (MVT::SimpleValueType)i;
1591
1592       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1593
1594       // Do not attempt to promote non-512-bit vectors.
1595       if (!VT.is512BitVector())
1596         continue;
1597
1598       if (EltSize < 32) {
1599         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1600         setOperationAction(ISD::VSELECT,             VT, Legal);
1601       }
1602     }
1603   }
1604
1605   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1606     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1607     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1608
1609     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1610     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1611     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1612     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1613     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1614     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1615     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1616     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1617     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1618     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1619
1620     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1621     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1622     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1623     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1624     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1625     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1626     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1627     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1628
1629     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1630     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1631     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1632     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1633     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1634     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1635     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1636     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1637   }
1638
1639   // We want to custom lower some of our intrinsics.
1640   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1641   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1642   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1643   if (!Subtarget->is64Bit())
1644     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1645
1646   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1647   // handle type legalization for these operations here.
1648   //
1649   // FIXME: We really should do custom legalization for addition and
1650   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1651   // than generic legalization for 64-bit multiplication-with-overflow, though.
1652   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1653     // Add/Sub/Mul with overflow operations are custom lowered.
1654     MVT VT = IntVTs[i];
1655     setOperationAction(ISD::SADDO, VT, Custom);
1656     setOperationAction(ISD::UADDO, VT, Custom);
1657     setOperationAction(ISD::SSUBO, VT, Custom);
1658     setOperationAction(ISD::USUBO, VT, Custom);
1659     setOperationAction(ISD::SMULO, VT, Custom);
1660     setOperationAction(ISD::UMULO, VT, Custom);
1661   }
1662
1663
1664   if (!Subtarget->is64Bit()) {
1665     // These libcalls are not available in 32-bit.
1666     setLibcallName(RTLIB::SHL_I128, nullptr);
1667     setLibcallName(RTLIB::SRL_I128, nullptr);
1668     setLibcallName(RTLIB::SRA_I128, nullptr);
1669   }
1670
1671   // Combine sin / cos into one node or libcall if possible.
1672   if (Subtarget->hasSinCos()) {
1673     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1674     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1675     if (Subtarget->isTargetDarwin()) {
1676       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1677       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1678       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1679       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1680     }
1681   }
1682
1683   if (Subtarget->isTargetWin64()) {
1684     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1685     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1686     setOperationAction(ISD::SREM, MVT::i128, Custom);
1687     setOperationAction(ISD::UREM, MVT::i128, Custom);
1688     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1689     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1690   }
1691
1692   // We have target-specific dag combine patterns for the following nodes:
1693   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1694   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1695   setTargetDAGCombine(ISD::BITCAST);
1696   setTargetDAGCombine(ISD::VSELECT);
1697   setTargetDAGCombine(ISD::SELECT);
1698   setTargetDAGCombine(ISD::SHL);
1699   setTargetDAGCombine(ISD::SRA);
1700   setTargetDAGCombine(ISD::SRL);
1701   setTargetDAGCombine(ISD::OR);
1702   setTargetDAGCombine(ISD::AND);
1703   setTargetDAGCombine(ISD::ADD);
1704   setTargetDAGCombine(ISD::FADD);
1705   setTargetDAGCombine(ISD::FSUB);
1706   setTargetDAGCombine(ISD::FMA);
1707   setTargetDAGCombine(ISD::SUB);
1708   setTargetDAGCombine(ISD::LOAD);
1709   setTargetDAGCombine(ISD::MLOAD);
1710   setTargetDAGCombine(ISD::STORE);
1711   setTargetDAGCombine(ISD::MSTORE);
1712   setTargetDAGCombine(ISD::ZERO_EXTEND);
1713   setTargetDAGCombine(ISD::ANY_EXTEND);
1714   setTargetDAGCombine(ISD::SIGN_EXTEND);
1715   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1716   setTargetDAGCombine(ISD::SINT_TO_FP);
1717   setTargetDAGCombine(ISD::UINT_TO_FP);
1718   setTargetDAGCombine(ISD::SETCC);
1719   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1720   setTargetDAGCombine(ISD::BUILD_VECTOR);
1721   setTargetDAGCombine(ISD::MUL);
1722   setTargetDAGCombine(ISD::XOR);
1723
1724   computeRegisterProperties(Subtarget->getRegisterInfo());
1725
1726   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1727   MaxStoresPerMemsetOptSize = 8;
1728   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1729   MaxStoresPerMemcpyOptSize = 4;
1730   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1731   MaxStoresPerMemmoveOptSize = 4;
1732   setPrefLoopAlignment(4); // 2^4 bytes.
1733
1734   // Predictable cmov don't hurt on atom because it's in-order.
1735   PredictableSelectIsExpensive = !Subtarget->isAtom();
1736   EnableExtLdPromotion = true;
1737   setPrefFunctionAlignment(4); // 2^4 bytes.
1738
1739   verifyIntrinsicTables();
1740 }
1741
1742 // This has so far only been implemented for 64-bit MachO.
1743 bool X86TargetLowering::useLoadStackGuardNode() const {
1744   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1745 }
1746
1747 TargetLoweringBase::LegalizeTypeAction
1748 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1749   if (ExperimentalVectorWideningLegalization &&
1750       VT.getVectorNumElements() != 1 &&
1751       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1752     return TypeWidenVector;
1753
1754   return TargetLoweringBase::getPreferredVectorAction(VT);
1755 }
1756
1757 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1758                                           EVT VT) const {
1759   if (!VT.isVector())
1760     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1761
1762   const unsigned NumElts = VT.getVectorNumElements();
1763   const EVT EltVT = VT.getVectorElementType();
1764   if (VT.is512BitVector()) {
1765     if (Subtarget->hasAVX512())
1766       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1767           EltVT == MVT::f32 || EltVT == MVT::f64)
1768         switch(NumElts) {
1769         case  8: return MVT::v8i1;
1770         case 16: return MVT::v16i1;
1771       }
1772     if (Subtarget->hasBWI())
1773       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1774         switch(NumElts) {
1775         case 32: return MVT::v32i1;
1776         case 64: return MVT::v64i1;
1777       }
1778   }
1779
1780   if (VT.is256BitVector() || VT.is128BitVector()) {
1781     if (Subtarget->hasVLX())
1782       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1783           EltVT == MVT::f32 || EltVT == MVT::f64)
1784         switch(NumElts) {
1785         case 2: return MVT::v2i1;
1786         case 4: return MVT::v4i1;
1787         case 8: return MVT::v8i1;
1788       }
1789     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1790       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1791         switch(NumElts) {
1792         case  8: return MVT::v8i1;
1793         case 16: return MVT::v16i1;
1794         case 32: return MVT::v32i1;
1795       }
1796   }
1797
1798   return VT.changeVectorElementTypeToInteger();
1799 }
1800
1801 /// Helper for getByValTypeAlignment to determine
1802 /// the desired ByVal argument alignment.
1803 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1804   if (MaxAlign == 16)
1805     return;
1806   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1807     if (VTy->getBitWidth() == 128)
1808       MaxAlign = 16;
1809   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1810     unsigned EltAlign = 0;
1811     getMaxByValAlign(ATy->getElementType(), EltAlign);
1812     if (EltAlign > MaxAlign)
1813       MaxAlign = EltAlign;
1814   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1815     for (auto *EltTy : STy->elements()) {
1816       unsigned EltAlign = 0;
1817       getMaxByValAlign(EltTy, EltAlign);
1818       if (EltAlign > MaxAlign)
1819         MaxAlign = EltAlign;
1820       if (MaxAlign == 16)
1821         break;
1822     }
1823   }
1824 }
1825
1826 /// Return the desired alignment for ByVal aggregate
1827 /// function arguments in the caller parameter area. For X86, aggregates
1828 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1829 /// are at 4-byte boundaries.
1830 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1831                                                   const DataLayout &DL) const {
1832   if (Subtarget->is64Bit()) {
1833     // Max of 8 and alignment of type.
1834     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1835     if (TyAlign > 8)
1836       return TyAlign;
1837     return 8;
1838   }
1839
1840   unsigned Align = 4;
1841   if (Subtarget->hasSSE1())
1842     getMaxByValAlign(Ty, Align);
1843   return Align;
1844 }
1845
1846 /// Returns the target specific optimal type for load
1847 /// and store operations as a result of memset, memcpy, and memmove
1848 /// lowering. If DstAlign is zero that means it's safe to destination
1849 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1850 /// means there isn't a need to check it against alignment requirement,
1851 /// probably because the source does not need to be loaded. If 'IsMemset' is
1852 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1853 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1854 /// source is constant so it does not need to be loaded.
1855 /// It returns EVT::Other if the type should be determined using generic
1856 /// target-independent logic.
1857 EVT
1858 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1859                                        unsigned DstAlign, unsigned SrcAlign,
1860                                        bool IsMemset, bool ZeroMemset,
1861                                        bool MemcpyStrSrc,
1862                                        MachineFunction &MF) const {
1863   const Function *F = MF.getFunction();
1864   if ((!IsMemset || ZeroMemset) &&
1865       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1866     if (Size >= 16 &&
1867         (Subtarget->isUnalignedMemAccessFast() ||
1868          ((DstAlign == 0 || DstAlign >= 16) &&
1869           (SrcAlign == 0 || SrcAlign >= 16)))) {
1870       if (Size >= 32) {
1871         if (Subtarget->hasInt256())
1872           return MVT::v8i32;
1873         if (Subtarget->hasFp256())
1874           return MVT::v8f32;
1875       }
1876       if (Subtarget->hasSSE2())
1877         return MVT::v4i32;
1878       if (Subtarget->hasSSE1())
1879         return MVT::v4f32;
1880     } else if (!MemcpyStrSrc && Size >= 8 &&
1881                !Subtarget->is64Bit() &&
1882                Subtarget->hasSSE2()) {
1883       // Do not use f64 to lower memcpy if source is string constant. It's
1884       // better to use i32 to avoid the loads.
1885       return MVT::f64;
1886     }
1887   }
1888   if (Subtarget->is64Bit() && Size >= 8)
1889     return MVT::i64;
1890   return MVT::i32;
1891 }
1892
1893 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1894   if (VT == MVT::f32)
1895     return X86ScalarSSEf32;
1896   else if (VT == MVT::f64)
1897     return X86ScalarSSEf64;
1898   return true;
1899 }
1900
1901 bool
1902 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1903                                                   unsigned,
1904                                                   unsigned,
1905                                                   bool *Fast) const {
1906   if (Fast)
1907     *Fast = Subtarget->isUnalignedMemAccessFast();
1908   return true;
1909 }
1910
1911 /// Return the entry encoding for a jump table in the
1912 /// current function.  The returned value is a member of the
1913 /// MachineJumpTableInfo::JTEntryKind enum.
1914 unsigned X86TargetLowering::getJumpTableEncoding() const {
1915   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1916   // symbol.
1917   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1918       Subtarget->isPICStyleGOT())
1919     return MachineJumpTableInfo::EK_Custom32;
1920
1921   // Otherwise, use the normal jump table encoding heuristics.
1922   return TargetLowering::getJumpTableEncoding();
1923 }
1924
1925 bool X86TargetLowering::useSoftFloat() const {
1926   return Subtarget->useSoftFloat();
1927 }
1928
1929 const MCExpr *
1930 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1931                                              const MachineBasicBlock *MBB,
1932                                              unsigned uid,MCContext &Ctx) const{
1933   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1934          Subtarget->isPICStyleGOT());
1935   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1936   // entries.
1937   return MCSymbolRefExpr::create(MBB->getSymbol(),
1938                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1939 }
1940
1941 /// Returns relocation base for the given PIC jumptable.
1942 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1943                                                     SelectionDAG &DAG) const {
1944   if (!Subtarget->is64Bit())
1945     // This doesn't have SDLoc associated with it, but is not really the
1946     // same as a Register.
1947     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1948                        getPointerTy(DAG.getDataLayout()));
1949   return Table;
1950 }
1951
1952 /// This returns the relocation base for the given PIC jumptable,
1953 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1954 const MCExpr *X86TargetLowering::
1955 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1956                              MCContext &Ctx) const {
1957   // X86-64 uses RIP relative addressing based on the jump table label.
1958   if (Subtarget->isPICStyleRIPRel())
1959     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1960
1961   // Otherwise, the reference is relative to the PIC base.
1962   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1963 }
1964
1965 std::pair<const TargetRegisterClass *, uint8_t>
1966 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1967                                            MVT VT) const {
1968   const TargetRegisterClass *RRC = nullptr;
1969   uint8_t Cost = 1;
1970   switch (VT.SimpleTy) {
1971   default:
1972     return TargetLowering::findRepresentativeClass(TRI, VT);
1973   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1974     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1975     break;
1976   case MVT::x86mmx:
1977     RRC = &X86::VR64RegClass;
1978     break;
1979   case MVT::f32: case MVT::f64:
1980   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1981   case MVT::v4f32: case MVT::v2f64:
1982   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1983   case MVT::v4f64:
1984     RRC = &X86::VR128RegClass;
1985     break;
1986   }
1987   return std::make_pair(RRC, Cost);
1988 }
1989
1990 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1991                                                unsigned &Offset) const {
1992   if (!Subtarget->isTargetLinux())
1993     return false;
1994
1995   if (Subtarget->is64Bit()) {
1996     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1997     Offset = 0x28;
1998     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1999       AddressSpace = 256;
2000     else
2001       AddressSpace = 257;
2002   } else {
2003     // %gs:0x14 on i386
2004     Offset = 0x14;
2005     AddressSpace = 256;
2006   }
2007   return true;
2008 }
2009
2010 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2011                                             unsigned DestAS) const {
2012   assert(SrcAS != DestAS && "Expected different address spaces!");
2013
2014   return SrcAS < 256 && DestAS < 256;
2015 }
2016
2017 //===----------------------------------------------------------------------===//
2018 //               Return Value Calling Convention Implementation
2019 //===----------------------------------------------------------------------===//
2020
2021 #include "X86GenCallingConv.inc"
2022
2023 bool
2024 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2025                                   MachineFunction &MF, bool isVarArg,
2026                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2027                         LLVMContext &Context) const {
2028   SmallVector<CCValAssign, 16> RVLocs;
2029   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2030   return CCInfo.CheckReturn(Outs, RetCC_X86);
2031 }
2032
2033 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2034   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2035   return ScratchRegs;
2036 }
2037
2038 SDValue
2039 X86TargetLowering::LowerReturn(SDValue Chain,
2040                                CallingConv::ID CallConv, bool isVarArg,
2041                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2042                                const SmallVectorImpl<SDValue> &OutVals,
2043                                SDLoc dl, SelectionDAG &DAG) const {
2044   MachineFunction &MF = DAG.getMachineFunction();
2045   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2046
2047   SmallVector<CCValAssign, 16> RVLocs;
2048   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2049   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2050
2051   SDValue Flag;
2052   SmallVector<SDValue, 6> RetOps;
2053   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2054   // Operand #1 = Bytes To Pop
2055   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2056                    MVT::i16));
2057
2058   // Copy the result values into the output registers.
2059   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2060     CCValAssign &VA = RVLocs[i];
2061     assert(VA.isRegLoc() && "Can only return in registers!");
2062     SDValue ValToCopy = OutVals[i];
2063     EVT ValVT = ValToCopy.getValueType();
2064
2065     // Promote values to the appropriate types.
2066     if (VA.getLocInfo() == CCValAssign::SExt)
2067       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2068     else if (VA.getLocInfo() == CCValAssign::ZExt)
2069       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2070     else if (VA.getLocInfo() == CCValAssign::AExt) {
2071       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2072         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2073       else
2074         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2075     }
2076     else if (VA.getLocInfo() == CCValAssign::BCvt)
2077       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2078
2079     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2080            "Unexpected FP-extend for return value.");
2081
2082     // If this is x86-64, and we disabled SSE, we can't return FP values,
2083     // or SSE or MMX vectors.
2084     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2085          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2086           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2087       report_fatal_error("SSE register return with SSE disabled");
2088     }
2089     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2090     // llvm-gcc has never done it right and no one has noticed, so this
2091     // should be OK for now.
2092     if (ValVT == MVT::f64 &&
2093         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2094       report_fatal_error("SSE2 register return with SSE2 disabled");
2095
2096     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2097     // the RET instruction and handled by the FP Stackifier.
2098     if (VA.getLocReg() == X86::FP0 ||
2099         VA.getLocReg() == X86::FP1) {
2100       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2101       // change the value to the FP stack register class.
2102       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2103         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2104       RetOps.push_back(ValToCopy);
2105       // Don't emit a copytoreg.
2106       continue;
2107     }
2108
2109     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2110     // which is returned in RAX / RDX.
2111     if (Subtarget->is64Bit()) {
2112       if (ValVT == MVT::x86mmx) {
2113         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2114           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2115           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2116                                   ValToCopy);
2117           // If we don't have SSE2 available, convert to v4f32 so the generated
2118           // register is legal.
2119           if (!Subtarget->hasSSE2())
2120             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2121         }
2122       }
2123     }
2124
2125     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2126     Flag = Chain.getValue(1);
2127     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2128   }
2129
2130   // All x86 ABIs require that for returning structs by value we copy
2131   // the sret argument into %rax/%eax (depending on ABI) for the return.
2132   // We saved the argument into a virtual register in the entry block,
2133   // so now we copy the value out and into %rax/%eax.
2134   //
2135   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2136   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2137   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2138   // either case FuncInfo->setSRetReturnReg() will have been called.
2139   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2140     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2141                                      getPointerTy(MF.getDataLayout()));
2142
2143     unsigned RetValReg
2144         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2145           X86::RAX : X86::EAX;
2146     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2147     Flag = Chain.getValue(1);
2148
2149     // RAX/EAX now acts like a return value.
2150     RetOps.push_back(
2151         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2152   }
2153
2154   RetOps[0] = Chain;  // Update chain.
2155
2156   // Add the flag if we have it.
2157   if (Flag.getNode())
2158     RetOps.push_back(Flag);
2159
2160   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2161 }
2162
2163 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2164   if (N->getNumValues() != 1)
2165     return false;
2166   if (!N->hasNUsesOfValue(1, 0))
2167     return false;
2168
2169   SDValue TCChain = Chain;
2170   SDNode *Copy = *N->use_begin();
2171   if (Copy->getOpcode() == ISD::CopyToReg) {
2172     // If the copy has a glue operand, we conservatively assume it isn't safe to
2173     // perform a tail call.
2174     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2175       return false;
2176     TCChain = Copy->getOperand(0);
2177   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2178     return false;
2179
2180   bool HasRet = false;
2181   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2182        UI != UE; ++UI) {
2183     if (UI->getOpcode() != X86ISD::RET_FLAG)
2184       return false;
2185     // If we are returning more than one value, we can definitely
2186     // not make a tail call see PR19530
2187     if (UI->getNumOperands() > 4)
2188       return false;
2189     if (UI->getNumOperands() == 4 &&
2190         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2191       return false;
2192     HasRet = true;
2193   }
2194
2195   if (!HasRet)
2196     return false;
2197
2198   Chain = TCChain;
2199   return true;
2200 }
2201
2202 EVT
2203 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2204                                             ISD::NodeType ExtendKind) const {
2205   MVT ReturnMVT;
2206   // TODO: Is this also valid on 32-bit?
2207   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2208     ReturnMVT = MVT::i8;
2209   else
2210     ReturnMVT = MVT::i32;
2211
2212   EVT MinVT = getRegisterType(Context, ReturnMVT);
2213   return VT.bitsLT(MinVT) ? MinVT : VT;
2214 }
2215
2216 /// Lower the result values of a call into the
2217 /// appropriate copies out of appropriate physical registers.
2218 ///
2219 SDValue
2220 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2221                                    CallingConv::ID CallConv, bool isVarArg,
2222                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2223                                    SDLoc dl, SelectionDAG &DAG,
2224                                    SmallVectorImpl<SDValue> &InVals) const {
2225
2226   // Assign locations to each value returned by this call.
2227   SmallVector<CCValAssign, 16> RVLocs;
2228   bool Is64Bit = Subtarget->is64Bit();
2229   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2230                  *DAG.getContext());
2231   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2232
2233   // Copy all of the result registers out of their specified physreg.
2234   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2235     CCValAssign &VA = RVLocs[i];
2236     EVT CopyVT = VA.getLocVT();
2237
2238     // If this is x86-64, and we disabled SSE, we can't return FP values
2239     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2240         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2241       report_fatal_error("SSE register return with SSE disabled");
2242     }
2243
2244     // If we prefer to use the value in xmm registers, copy it out as f80 and
2245     // use a truncate to move it from fp stack reg to xmm reg.
2246     bool RoundAfterCopy = false;
2247     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2248         isScalarFPTypeInSSEReg(VA.getValVT())) {
2249       CopyVT = MVT::f80;
2250       RoundAfterCopy = (CopyVT != VA.getLocVT());
2251     }
2252
2253     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2254                                CopyVT, InFlag).getValue(1);
2255     SDValue Val = Chain.getValue(0);
2256
2257     if (RoundAfterCopy)
2258       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2259                         // This truncation won't change the value.
2260                         DAG.getIntPtrConstant(1, dl));
2261
2262     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2263       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2264
2265     InFlag = Chain.getValue(2);
2266     InVals.push_back(Val);
2267   }
2268
2269   return Chain;
2270 }
2271
2272 //===----------------------------------------------------------------------===//
2273 //                C & StdCall & Fast Calling Convention implementation
2274 //===----------------------------------------------------------------------===//
2275 //  StdCall calling convention seems to be standard for many Windows' API
2276 //  routines and around. It differs from C calling convention just a little:
2277 //  callee should clean up the stack, not caller. Symbols should be also
2278 //  decorated in some fancy way :) It doesn't support any vector arguments.
2279 //  For info on fast calling convention see Fast Calling Convention (tail call)
2280 //  implementation LowerX86_32FastCCCallTo.
2281
2282 /// CallIsStructReturn - Determines whether a call uses struct return
2283 /// semantics.
2284 enum StructReturnType {
2285   NotStructReturn,
2286   RegStructReturn,
2287   StackStructReturn
2288 };
2289 static StructReturnType
2290 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2291   if (Outs.empty())
2292     return NotStructReturn;
2293
2294   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2295   if (!Flags.isSRet())
2296     return NotStructReturn;
2297   if (Flags.isInReg())
2298     return RegStructReturn;
2299   return StackStructReturn;
2300 }
2301
2302 /// Determines whether a function uses struct return semantics.
2303 static StructReturnType
2304 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2305   if (Ins.empty())
2306     return NotStructReturn;
2307
2308   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2309   if (!Flags.isSRet())
2310     return NotStructReturn;
2311   if (Flags.isInReg())
2312     return RegStructReturn;
2313   return StackStructReturn;
2314 }
2315
2316 /// Make a copy of an aggregate at address specified by "Src" to address
2317 /// "Dst" with size and alignment information specified by the specific
2318 /// parameter attribute. The copy will be passed as a byval function parameter.
2319 static SDValue
2320 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2321                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2322                           SDLoc dl) {
2323   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2324
2325   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2326                        /*isVolatile*/false, /*AlwaysInline=*/true,
2327                        /*isTailCall*/false,
2328                        MachinePointerInfo(), MachinePointerInfo());
2329 }
2330
2331 /// Return true if the calling convention is one that
2332 /// supports tail call optimization.
2333 static bool IsTailCallConvention(CallingConv::ID CC) {
2334   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2335           CC == CallingConv::HiPE);
2336 }
2337
2338 /// \brief Return true if the calling convention is a C calling convention.
2339 static bool IsCCallConvention(CallingConv::ID CC) {
2340   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2341           CC == CallingConv::X86_64_SysV);
2342 }
2343
2344 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2345   auto Attr =
2346       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2347   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2348     return false;
2349
2350   CallSite CS(CI);
2351   CallingConv::ID CalleeCC = CS.getCallingConv();
2352   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2353     return false;
2354
2355   return true;
2356 }
2357
2358 /// Return true if the function is being made into
2359 /// a tailcall target by changing its ABI.
2360 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2361                                    bool GuaranteedTailCallOpt) {
2362   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2363 }
2364
2365 SDValue
2366 X86TargetLowering::LowerMemArgument(SDValue Chain,
2367                                     CallingConv::ID CallConv,
2368                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2369                                     SDLoc dl, SelectionDAG &DAG,
2370                                     const CCValAssign &VA,
2371                                     MachineFrameInfo *MFI,
2372                                     unsigned i) const {
2373   // Create the nodes corresponding to a load from this parameter slot.
2374   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2375   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2376       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2377   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2378   EVT ValVT;
2379
2380   // If value is passed by pointer we have address passed instead of the value
2381   // itself.
2382   bool ExtendedInMem = VA.isExtInLoc() &&
2383     VA.getValVT().getScalarType() == MVT::i1;
2384
2385   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2386     ValVT = VA.getLocVT();
2387   else
2388     ValVT = VA.getValVT();
2389
2390   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2391   // changed with more analysis.
2392   // In case of tail call optimization mark all arguments mutable. Since they
2393   // could be overwritten by lowering of arguments in case of a tail call.
2394   if (Flags.isByVal()) {
2395     unsigned Bytes = Flags.getByValSize();
2396     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2397     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2398     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2399   } else {
2400     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2401                                     VA.getLocMemOffset(), isImmutable);
2402     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2403     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2404                                MachinePointerInfo::getFixedStack(FI),
2405                                false, false, false, 0);
2406     return ExtendedInMem ?
2407       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2408   }
2409 }
2410
2411 // FIXME: Get this from tablegen.
2412 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2413                                                 const X86Subtarget *Subtarget) {
2414   assert(Subtarget->is64Bit());
2415
2416   if (Subtarget->isCallingConvWin64(CallConv)) {
2417     static const MCPhysReg GPR64ArgRegsWin64[] = {
2418       X86::RCX, X86::RDX, X86::R8,  X86::R9
2419     };
2420     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2421   }
2422
2423   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2424     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2425   };
2426   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2427 }
2428
2429 // FIXME: Get this from tablegen.
2430 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2431                                                 CallingConv::ID CallConv,
2432                                                 const X86Subtarget *Subtarget) {
2433   assert(Subtarget->is64Bit());
2434   if (Subtarget->isCallingConvWin64(CallConv)) {
2435     // The XMM registers which might contain var arg parameters are shadowed
2436     // in their paired GPR.  So we only need to save the GPR to their home
2437     // slots.
2438     // TODO: __vectorcall will change this.
2439     return None;
2440   }
2441
2442   const Function *Fn = MF.getFunction();
2443   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2444   bool isSoftFloat = Subtarget->useSoftFloat();
2445   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2446          "SSE register cannot be used when SSE is disabled!");
2447   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2448     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2449     // registers.
2450     return None;
2451
2452   static const MCPhysReg XMMArgRegs64Bit[] = {
2453     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2454     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2455   };
2456   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2457 }
2458
2459 SDValue
2460 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2461                                         CallingConv::ID CallConv,
2462                                         bool isVarArg,
2463                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2464                                         SDLoc dl,
2465                                         SelectionDAG &DAG,
2466                                         SmallVectorImpl<SDValue> &InVals)
2467                                           const {
2468   MachineFunction &MF = DAG.getMachineFunction();
2469   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2470   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2471
2472   const Function* Fn = MF.getFunction();
2473   if (Fn->hasExternalLinkage() &&
2474       Subtarget->isTargetCygMing() &&
2475       Fn->getName() == "main")
2476     FuncInfo->setForceFramePointer(true);
2477
2478   MachineFrameInfo *MFI = MF.getFrameInfo();
2479   bool Is64Bit = Subtarget->is64Bit();
2480   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2481
2482   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2483          "Var args not supported with calling convention fastcc, ghc or hipe");
2484
2485   // Assign locations to all of the incoming arguments.
2486   SmallVector<CCValAssign, 16> ArgLocs;
2487   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2488
2489   // Allocate shadow area for Win64
2490   if (IsWin64)
2491     CCInfo.AllocateStack(32, 8);
2492
2493   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2494
2495   unsigned LastVal = ~0U;
2496   SDValue ArgValue;
2497   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2498     CCValAssign &VA = ArgLocs[i];
2499     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2500     // places.
2501     assert(VA.getValNo() != LastVal &&
2502            "Don't support value assigned to multiple locs yet");
2503     (void)LastVal;
2504     LastVal = VA.getValNo();
2505
2506     if (VA.isRegLoc()) {
2507       EVT RegVT = VA.getLocVT();
2508       const TargetRegisterClass *RC;
2509       if (RegVT == MVT::i32)
2510         RC = &X86::GR32RegClass;
2511       else if (Is64Bit && RegVT == MVT::i64)
2512         RC = &X86::GR64RegClass;
2513       else if (RegVT == MVT::f32)
2514         RC = &X86::FR32RegClass;
2515       else if (RegVT == MVT::f64)
2516         RC = &X86::FR64RegClass;
2517       else if (RegVT.is512BitVector())
2518         RC = &X86::VR512RegClass;
2519       else if (RegVT.is256BitVector())
2520         RC = &X86::VR256RegClass;
2521       else if (RegVT.is128BitVector())
2522         RC = &X86::VR128RegClass;
2523       else if (RegVT == MVT::x86mmx)
2524         RC = &X86::VR64RegClass;
2525       else if (RegVT == MVT::i1)
2526         RC = &X86::VK1RegClass;
2527       else if (RegVT == MVT::v8i1)
2528         RC = &X86::VK8RegClass;
2529       else if (RegVT == MVT::v16i1)
2530         RC = &X86::VK16RegClass;
2531       else if (RegVT == MVT::v32i1)
2532         RC = &X86::VK32RegClass;
2533       else if (RegVT == MVT::v64i1)
2534         RC = &X86::VK64RegClass;
2535       else
2536         llvm_unreachable("Unknown argument type!");
2537
2538       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2539       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2540
2541       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2542       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2543       // right size.
2544       if (VA.getLocInfo() == CCValAssign::SExt)
2545         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2546                                DAG.getValueType(VA.getValVT()));
2547       else if (VA.getLocInfo() == CCValAssign::ZExt)
2548         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2549                                DAG.getValueType(VA.getValVT()));
2550       else if (VA.getLocInfo() == CCValAssign::BCvt)
2551         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2552
2553       if (VA.isExtInLoc()) {
2554         // Handle MMX values passed in XMM regs.
2555         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2556           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2557         else
2558           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2559       }
2560     } else {
2561       assert(VA.isMemLoc());
2562       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2563     }
2564
2565     // If value is passed via pointer - do a load.
2566     if (VA.getLocInfo() == CCValAssign::Indirect)
2567       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2568                              MachinePointerInfo(), false, false, false, 0);
2569
2570     InVals.push_back(ArgValue);
2571   }
2572
2573   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2574     // All x86 ABIs require that for returning structs by value we copy the
2575     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2576     // the argument into a virtual register so that we can access it from the
2577     // return points.
2578     if (Ins[i].Flags.isSRet()) {
2579       unsigned Reg = FuncInfo->getSRetReturnReg();
2580       if (!Reg) {
2581         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2582         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2583         FuncInfo->setSRetReturnReg(Reg);
2584       }
2585       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2586       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2587       break;
2588     }
2589   }
2590
2591   unsigned StackSize = CCInfo.getNextStackOffset();
2592   // Align stack specially for tail calls.
2593   if (FuncIsMadeTailCallSafe(CallConv,
2594                              MF.getTarget().Options.GuaranteedTailCallOpt))
2595     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2596
2597   // If the function takes variable number of arguments, make a frame index for
2598   // the start of the first vararg value... for expansion of llvm.va_start. We
2599   // can skip this if there are no va_start calls.
2600   if (MFI->hasVAStart() &&
2601       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2602                    CallConv != CallingConv::X86_ThisCall))) {
2603     FuncInfo->setVarArgsFrameIndex(
2604         MFI->CreateFixedObject(1, StackSize, true));
2605   }
2606
2607   MachineModuleInfo &MMI = MF.getMMI();
2608   const Function *WinEHParent = nullptr;
2609   if (MMI.hasWinEHFuncInfo(Fn))
2610     WinEHParent = MMI.getWinEHParent(Fn);
2611   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2612   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2613
2614   // Figure out if XMM registers are in use.
2615   assert(!(Subtarget->useSoftFloat() &&
2616            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2617          "SSE register cannot be used when SSE is disabled!");
2618
2619   // 64-bit calling conventions support varargs and register parameters, so we
2620   // have to do extra work to spill them in the prologue.
2621   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2622     // Find the first unallocated argument registers.
2623     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2624     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2625     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2626     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2627     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2628            "SSE register cannot be used when SSE is disabled!");
2629
2630     // Gather all the live in physical registers.
2631     SmallVector<SDValue, 6> LiveGPRs;
2632     SmallVector<SDValue, 8> LiveXMMRegs;
2633     SDValue ALVal;
2634     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2635       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2636       LiveGPRs.push_back(
2637           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2638     }
2639     if (!ArgXMMs.empty()) {
2640       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2641       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2642       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2643         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2644         LiveXMMRegs.push_back(
2645             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2646       }
2647     }
2648
2649     if (IsWin64) {
2650       // Get to the caller-allocated home save location.  Add 8 to account
2651       // for the return address.
2652       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2653       FuncInfo->setRegSaveFrameIndex(
2654           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2655       // Fixup to set vararg frame on shadow area (4 x i64).
2656       if (NumIntRegs < 4)
2657         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2658     } else {
2659       // For X86-64, if there are vararg parameters that are passed via
2660       // registers, then we must store them to their spots on the stack so
2661       // they may be loaded by deferencing the result of va_next.
2662       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2663       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2664       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2665           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2666     }
2667
2668     // Store the integer parameter registers.
2669     SmallVector<SDValue, 8> MemOps;
2670     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2671                                       getPointerTy(DAG.getDataLayout()));
2672     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2673     for (SDValue Val : LiveGPRs) {
2674       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2675                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2676       SDValue Store =
2677         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2678                      MachinePointerInfo::getFixedStack(
2679                        FuncInfo->getRegSaveFrameIndex(), Offset),
2680                      false, false, 0);
2681       MemOps.push_back(Store);
2682       Offset += 8;
2683     }
2684
2685     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2686       // Now store the XMM (fp + vector) parameter registers.
2687       SmallVector<SDValue, 12> SaveXMMOps;
2688       SaveXMMOps.push_back(Chain);
2689       SaveXMMOps.push_back(ALVal);
2690       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2691                              FuncInfo->getRegSaveFrameIndex(), dl));
2692       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2693                              FuncInfo->getVarArgsFPOffset(), dl));
2694       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2695                         LiveXMMRegs.end());
2696       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2697                                    MVT::Other, SaveXMMOps));
2698     }
2699
2700     if (!MemOps.empty())
2701       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2702   } else if (IsWin64 && IsWinEHOutlined) {
2703     // Get to the caller-allocated home save location.  Add 8 to account
2704     // for the return address.
2705     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2706     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2707         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2708
2709     MMI.getWinEHFuncInfo(Fn)
2710         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2711         FuncInfo->getRegSaveFrameIndex();
2712
2713     // Store the second integer parameter (rdx) into rsp+16 relative to the
2714     // stack pointer at the entry of the function.
2715     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2716                                       getPointerTy(DAG.getDataLayout()));
2717     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2718     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2719     Chain = DAG.getStore(
2720         Val.getValue(1), dl, Val, RSFIN,
2721         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2722         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2723   }
2724
2725   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2726     // Find the largest legal vector type.
2727     MVT VecVT = MVT::Other;
2728     // FIXME: Only some x86_32 calling conventions support AVX512.
2729     if (Subtarget->hasAVX512() &&
2730         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2731                      CallConv == CallingConv::Intel_OCL_BI)))
2732       VecVT = MVT::v16f32;
2733     else if (Subtarget->hasAVX())
2734       VecVT = MVT::v8f32;
2735     else if (Subtarget->hasSSE2())
2736       VecVT = MVT::v4f32;
2737
2738     // We forward some GPRs and some vector types.
2739     SmallVector<MVT, 2> RegParmTypes;
2740     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2741     RegParmTypes.push_back(IntVT);
2742     if (VecVT != MVT::Other)
2743       RegParmTypes.push_back(VecVT);
2744
2745     // Compute the set of forwarded registers. The rest are scratch.
2746     SmallVectorImpl<ForwardedRegister> &Forwards =
2747         FuncInfo->getForwardedMustTailRegParms();
2748     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2749
2750     // Conservatively forward AL on x86_64, since it might be used for varargs.
2751     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2752       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2753       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2754     }
2755
2756     // Copy all forwards from physical to virtual registers.
2757     for (ForwardedRegister &F : Forwards) {
2758       // FIXME: Can we use a less constrained schedule?
2759       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2760       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2761       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2762     }
2763   }
2764
2765   // Some CCs need callee pop.
2766   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2767                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2768     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2769   } else {
2770     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2771     // If this is an sret function, the return should pop the hidden pointer.
2772     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2773         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2774         argsAreStructReturn(Ins) == StackStructReturn)
2775       FuncInfo->setBytesToPopOnReturn(4);
2776   }
2777
2778   if (!Is64Bit) {
2779     // RegSaveFrameIndex is X86-64 only.
2780     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2781     if (CallConv == CallingConv::X86_FastCall ||
2782         CallConv == CallingConv::X86_ThisCall)
2783       // fastcc functions can't have varargs.
2784       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2785   }
2786
2787   FuncInfo->setArgumentStackSize(StackSize);
2788
2789   if (IsWinEHParent) {
2790     if (Is64Bit) {
2791       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2792       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2793       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2794       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2795       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2796                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2797                            /*isVolatile=*/true,
2798                            /*isNonTemporal=*/false, /*Alignment=*/0);
2799     } else {
2800       // Functions using Win32 EH are considered to have opaque SP adjustments
2801       // to force local variables to be addressed from the frame or base
2802       // pointers.
2803       MFI->setHasOpaqueSPAdjustment(true);
2804     }
2805   }
2806
2807   return Chain;
2808 }
2809
2810 SDValue
2811 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2812                                     SDValue StackPtr, SDValue Arg,
2813                                     SDLoc dl, SelectionDAG &DAG,
2814                                     const CCValAssign &VA,
2815                                     ISD::ArgFlagsTy Flags) const {
2816   unsigned LocMemOffset = VA.getLocMemOffset();
2817   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2818   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2819                        StackPtr, PtrOff);
2820   if (Flags.isByVal())
2821     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2822
2823   return DAG.getStore(Chain, dl, Arg, PtrOff,
2824                       MachinePointerInfo::getStack(LocMemOffset),
2825                       false, false, 0);
2826 }
2827
2828 /// Emit a load of return address if tail call
2829 /// optimization is performed and it is required.
2830 SDValue
2831 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2832                                            SDValue &OutRetAddr, SDValue Chain,
2833                                            bool IsTailCall, bool Is64Bit,
2834                                            int FPDiff, SDLoc dl) const {
2835   // Adjust the Return address stack slot.
2836   EVT VT = getPointerTy(DAG.getDataLayout());
2837   OutRetAddr = getReturnAddressFrameIndex(DAG);
2838
2839   // Load the "old" Return address.
2840   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2841                            false, false, false, 0);
2842   return SDValue(OutRetAddr.getNode(), 1);
2843 }
2844
2845 /// Emit a store of the return address if tail call
2846 /// optimization is performed and it is required (FPDiff!=0).
2847 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2848                                         SDValue Chain, SDValue RetAddrFrIdx,
2849                                         EVT PtrVT, unsigned SlotSize,
2850                                         int FPDiff, SDLoc dl) {
2851   // Store the return address to the appropriate stack slot.
2852   if (!FPDiff) return Chain;
2853   // Calculate the new stack slot for the return address.
2854   int NewReturnAddrFI =
2855     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2856                                          false);
2857   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2858   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2859                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2860                        false, false, 0);
2861   return Chain;
2862 }
2863
2864 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2865 /// operation of specified width.
2866 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2867                        SDValue V2) {
2868   unsigned NumElems = VT.getVectorNumElements();
2869   SmallVector<int, 8> Mask;
2870   Mask.push_back(NumElems);
2871   for (unsigned i = 1; i != NumElems; ++i)
2872     Mask.push_back(i);
2873   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2874 }
2875
2876 SDValue
2877 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2878                              SmallVectorImpl<SDValue> &InVals) const {
2879   SelectionDAG &DAG                     = CLI.DAG;
2880   SDLoc &dl                             = CLI.DL;
2881   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2882   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2883   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2884   SDValue Chain                         = CLI.Chain;
2885   SDValue Callee                        = CLI.Callee;
2886   CallingConv::ID CallConv              = CLI.CallConv;
2887   bool &isTailCall                      = CLI.IsTailCall;
2888   bool isVarArg                         = CLI.IsVarArg;
2889
2890   MachineFunction &MF = DAG.getMachineFunction();
2891   bool Is64Bit        = Subtarget->is64Bit();
2892   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2893   StructReturnType SR = callIsStructReturn(Outs);
2894   bool IsSibcall      = false;
2895   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2896   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2897
2898   if (Attr.getValueAsString() == "true")
2899     isTailCall = false;
2900
2901   if (Subtarget->isPICStyleGOT() &&
2902       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2903     // If we are using a GOT, disable tail calls to external symbols with
2904     // default visibility. Tail calling such a symbol requires using a GOT
2905     // relocation, which forces early binding of the symbol. This breaks code
2906     // that require lazy function symbol resolution. Using musttail or
2907     // GuaranteedTailCallOpt will override this.
2908     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2909     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2910                G->getGlobal()->hasDefaultVisibility()))
2911       isTailCall = false;
2912   }
2913
2914   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2915   if (IsMustTail) {
2916     // Force this to be a tail call.  The verifier rules are enough to ensure
2917     // that we can lower this successfully without moving the return address
2918     // around.
2919     isTailCall = true;
2920   } else if (isTailCall) {
2921     // Check if it's really possible to do a tail call.
2922     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2923                     isVarArg, SR != NotStructReturn,
2924                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2925                     Outs, OutVals, Ins, DAG);
2926
2927     // Sibcalls are automatically detected tailcalls which do not require
2928     // ABI changes.
2929     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2930       IsSibcall = true;
2931
2932     if (isTailCall)
2933       ++NumTailCalls;
2934   }
2935
2936   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2937          "Var args not supported with calling convention fastcc, ghc or hipe");
2938
2939   // Analyze operands of the call, assigning locations to each operand.
2940   SmallVector<CCValAssign, 16> ArgLocs;
2941   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2942
2943   // Allocate shadow area for Win64
2944   if (IsWin64)
2945     CCInfo.AllocateStack(32, 8);
2946
2947   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2948
2949   // Get a count of how many bytes are to be pushed on the stack.
2950   unsigned NumBytes = CCInfo.getNextStackOffset();
2951   if (IsSibcall)
2952     // This is a sibcall. The memory operands are available in caller's
2953     // own caller's stack.
2954     NumBytes = 0;
2955   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2956            IsTailCallConvention(CallConv))
2957     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2958
2959   int FPDiff = 0;
2960   if (isTailCall && !IsSibcall && !IsMustTail) {
2961     // Lower arguments at fp - stackoffset + fpdiff.
2962     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2963
2964     FPDiff = NumBytesCallerPushed - NumBytes;
2965
2966     // Set the delta of movement of the returnaddr stackslot.
2967     // But only set if delta is greater than previous delta.
2968     if (FPDiff < X86Info->getTCReturnAddrDelta())
2969       X86Info->setTCReturnAddrDelta(FPDiff);
2970   }
2971
2972   unsigned NumBytesToPush = NumBytes;
2973   unsigned NumBytesToPop = NumBytes;
2974
2975   // If we have an inalloca argument, all stack space has already been allocated
2976   // for us and be right at the top of the stack.  We don't support multiple
2977   // arguments passed in memory when using inalloca.
2978   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2979     NumBytesToPush = 0;
2980     if (!ArgLocs.back().isMemLoc())
2981       report_fatal_error("cannot use inalloca attribute on a register "
2982                          "parameter");
2983     if (ArgLocs.back().getLocMemOffset() != 0)
2984       report_fatal_error("any parameter with the inalloca attribute must be "
2985                          "the only memory argument");
2986   }
2987
2988   if (!IsSibcall)
2989     Chain = DAG.getCALLSEQ_START(
2990         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2991
2992   SDValue RetAddrFrIdx;
2993   // Load return address for tail calls.
2994   if (isTailCall && FPDiff)
2995     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2996                                     Is64Bit, FPDiff, dl);
2997
2998   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2999   SmallVector<SDValue, 8> MemOpChains;
3000   SDValue StackPtr;
3001
3002   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3003   // of tail call optimization arguments are handle later.
3004   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3005   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3006     // Skip inalloca arguments, they have already been written.
3007     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3008     if (Flags.isInAlloca())
3009       continue;
3010
3011     CCValAssign &VA = ArgLocs[i];
3012     EVT RegVT = VA.getLocVT();
3013     SDValue Arg = OutVals[i];
3014     bool isByVal = Flags.isByVal();
3015
3016     // Promote the value if needed.
3017     switch (VA.getLocInfo()) {
3018     default: llvm_unreachable("Unknown loc info!");
3019     case CCValAssign::Full: break;
3020     case CCValAssign::SExt:
3021       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3022       break;
3023     case CCValAssign::ZExt:
3024       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3025       break;
3026     case CCValAssign::AExt:
3027       if (Arg.getValueType().isVector() &&
3028           Arg.getValueType().getScalarType() == MVT::i1)
3029         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3030       else if (RegVT.is128BitVector()) {
3031         // Special case: passing MMX values in XMM registers.
3032         Arg = DAG.getBitcast(MVT::i64, Arg);
3033         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3034         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3035       } else
3036         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3037       break;
3038     case CCValAssign::BCvt:
3039       Arg = DAG.getBitcast(RegVT, Arg);
3040       break;
3041     case CCValAssign::Indirect: {
3042       // Store the argument.
3043       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3044       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3045       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3046                            MachinePointerInfo::getFixedStack(FI),
3047                            false, false, 0);
3048       Arg = SpillSlot;
3049       break;
3050     }
3051     }
3052
3053     if (VA.isRegLoc()) {
3054       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3055       if (isVarArg && IsWin64) {
3056         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3057         // shadow reg if callee is a varargs function.
3058         unsigned ShadowReg = 0;
3059         switch (VA.getLocReg()) {
3060         case X86::XMM0: ShadowReg = X86::RCX; break;
3061         case X86::XMM1: ShadowReg = X86::RDX; break;
3062         case X86::XMM2: ShadowReg = X86::R8; break;
3063         case X86::XMM3: ShadowReg = X86::R9; break;
3064         }
3065         if (ShadowReg)
3066           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3067       }
3068     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3069       assert(VA.isMemLoc());
3070       if (!StackPtr.getNode())
3071         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3072                                       getPointerTy(DAG.getDataLayout()));
3073       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3074                                              dl, DAG, VA, Flags));
3075     }
3076   }
3077
3078   if (!MemOpChains.empty())
3079     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3080
3081   if (Subtarget->isPICStyleGOT()) {
3082     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3083     // GOT pointer.
3084     if (!isTailCall) {
3085       RegsToPass.push_back(std::make_pair(
3086           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3087                                           getPointerTy(DAG.getDataLayout()))));
3088     } else {
3089       // If we are tail calling and generating PIC/GOT style code load the
3090       // address of the callee into ECX. The value in ecx is used as target of
3091       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3092       // for tail calls on PIC/GOT architectures. Normally we would just put the
3093       // address of GOT into ebx and then call target@PLT. But for tail calls
3094       // ebx would be restored (since ebx is callee saved) before jumping to the
3095       // target@PLT.
3096
3097       // Note: The actual moving to ECX is done further down.
3098       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3099       if (G && !G->getGlobal()->hasLocalLinkage() &&
3100           G->getGlobal()->hasDefaultVisibility())
3101         Callee = LowerGlobalAddress(Callee, DAG);
3102       else if (isa<ExternalSymbolSDNode>(Callee))
3103         Callee = LowerExternalSymbol(Callee, DAG);
3104     }
3105   }
3106
3107   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3108     // From AMD64 ABI document:
3109     // For calls that may call functions that use varargs or stdargs
3110     // (prototype-less calls or calls to functions containing ellipsis (...) in
3111     // the declaration) %al is used as hidden argument to specify the number
3112     // of SSE registers used. The contents of %al do not need to match exactly
3113     // the number of registers, but must be an ubound on the number of SSE
3114     // registers used and is in the range 0 - 8 inclusive.
3115
3116     // Count the number of XMM registers allocated.
3117     static const MCPhysReg XMMArgRegs[] = {
3118       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3119       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3120     };
3121     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3122     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3123            && "SSE registers cannot be used when SSE is disabled");
3124
3125     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3126                                         DAG.getConstant(NumXMMRegs, dl,
3127                                                         MVT::i8)));
3128   }
3129
3130   if (isVarArg && IsMustTail) {
3131     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3132     for (const auto &F : Forwards) {
3133       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3134       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3135     }
3136   }
3137
3138   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3139   // don't need this because the eligibility check rejects calls that require
3140   // shuffling arguments passed in memory.
3141   if (!IsSibcall && isTailCall) {
3142     // Force all the incoming stack arguments to be loaded from the stack
3143     // before any new outgoing arguments are stored to the stack, because the
3144     // outgoing stack slots may alias the incoming argument stack slots, and
3145     // the alias isn't otherwise explicit. This is slightly more conservative
3146     // than necessary, because it means that each store effectively depends
3147     // on every argument instead of just those arguments it would clobber.
3148     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3149
3150     SmallVector<SDValue, 8> MemOpChains2;
3151     SDValue FIN;
3152     int FI = 0;
3153     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3154       CCValAssign &VA = ArgLocs[i];
3155       if (VA.isRegLoc())
3156         continue;
3157       assert(VA.isMemLoc());
3158       SDValue Arg = OutVals[i];
3159       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3160       // Skip inalloca arguments.  They don't require any work.
3161       if (Flags.isInAlloca())
3162         continue;
3163       // Create frame index.
3164       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3165       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3166       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3167       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3168
3169       if (Flags.isByVal()) {
3170         // Copy relative to framepointer.
3171         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3172         if (!StackPtr.getNode())
3173           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3174                                         getPointerTy(DAG.getDataLayout()));
3175         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3176                              StackPtr, Source);
3177
3178         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3179                                                          ArgChain,
3180                                                          Flags, DAG, dl));
3181       } else {
3182         // Store relative to framepointer.
3183         MemOpChains2.push_back(
3184           DAG.getStore(ArgChain, dl, Arg, FIN,
3185                        MachinePointerInfo::getFixedStack(FI),
3186                        false, false, 0));
3187       }
3188     }
3189
3190     if (!MemOpChains2.empty())
3191       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3192
3193     // Store the return address to the appropriate stack slot.
3194     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3195                                      getPointerTy(DAG.getDataLayout()),
3196                                      RegInfo->getSlotSize(), FPDiff, dl);
3197   }
3198
3199   // Build a sequence of copy-to-reg nodes chained together with token chain
3200   // and flag operands which copy the outgoing args into registers.
3201   SDValue InFlag;
3202   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3203     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3204                              RegsToPass[i].second, InFlag);
3205     InFlag = Chain.getValue(1);
3206   }
3207
3208   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3209     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3210     // In the 64-bit large code model, we have to make all calls
3211     // through a register, since the call instruction's 32-bit
3212     // pc-relative offset may not be large enough to hold the whole
3213     // address.
3214   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3215     // If the callee is a GlobalAddress node (quite common, every direct call
3216     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3217     // it.
3218     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3219
3220     // We should use extra load for direct calls to dllimported functions in
3221     // non-JIT mode.
3222     const GlobalValue *GV = G->getGlobal();
3223     if (!GV->hasDLLImportStorageClass()) {
3224       unsigned char OpFlags = 0;
3225       bool ExtraLoad = false;
3226       unsigned WrapperKind = ISD::DELETED_NODE;
3227
3228       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3229       // external symbols most go through the PLT in PIC mode.  If the symbol
3230       // has hidden or protected visibility, or if it is static or local, then
3231       // we don't need to use the PLT - we can directly call it.
3232       if (Subtarget->isTargetELF() &&
3233           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3234           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3235         OpFlags = X86II::MO_PLT;
3236       } else if (Subtarget->isPICStyleStubAny() &&
3237                  !GV->isStrongDefinitionForLinker() &&
3238                  (!Subtarget->getTargetTriple().isMacOSX() ||
3239                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3240         // PC-relative references to external symbols should go through $stub,
3241         // unless we're building with the leopard linker or later, which
3242         // automatically synthesizes these stubs.
3243         OpFlags = X86II::MO_DARWIN_STUB;
3244       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3245                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3246         // If the function is marked as non-lazy, generate an indirect call
3247         // which loads from the GOT directly. This avoids runtime overhead
3248         // at the cost of eager binding (and one extra byte of encoding).
3249         OpFlags = X86II::MO_GOTPCREL;
3250         WrapperKind = X86ISD::WrapperRIP;
3251         ExtraLoad = true;
3252       }
3253
3254       Callee = DAG.getTargetGlobalAddress(
3255           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3256
3257       // Add a wrapper if needed.
3258       if (WrapperKind != ISD::DELETED_NODE)
3259         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3260                              getPointerTy(DAG.getDataLayout()), Callee);
3261       // Add extra indirection if needed.
3262       if (ExtraLoad)
3263         Callee = DAG.getLoad(
3264             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3265             MachinePointerInfo::getGOT(), false, false, false, 0);
3266     }
3267   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3268     unsigned char OpFlags = 0;
3269
3270     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3271     // external symbols should go through the PLT.
3272     if (Subtarget->isTargetELF() &&
3273         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3274       OpFlags = X86II::MO_PLT;
3275     } else if (Subtarget->isPICStyleStubAny() &&
3276                (!Subtarget->getTargetTriple().isMacOSX() ||
3277                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3278       // PC-relative references to external symbols should go through $stub,
3279       // unless we're building with the leopard linker or later, which
3280       // automatically synthesizes these stubs.
3281       OpFlags = X86II::MO_DARWIN_STUB;
3282     }
3283
3284     Callee = DAG.getTargetExternalSymbol(
3285         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3286   } else if (Subtarget->isTarget64BitILP32() &&
3287              Callee->getValueType(0) == MVT::i32) {
3288     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3289     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3290   }
3291
3292   // Returns a chain & a flag for retval copy to use.
3293   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3294   SmallVector<SDValue, 8> Ops;
3295
3296   if (!IsSibcall && isTailCall) {
3297     Chain = DAG.getCALLSEQ_END(Chain,
3298                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3299                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3300     InFlag = Chain.getValue(1);
3301   }
3302
3303   Ops.push_back(Chain);
3304   Ops.push_back(Callee);
3305
3306   if (isTailCall)
3307     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3308
3309   // Add argument registers to the end of the list so that they are known live
3310   // into the call.
3311   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3312     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3313                                   RegsToPass[i].second.getValueType()));
3314
3315   // Add a register mask operand representing the call-preserved registers.
3316   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3317   assert(Mask && "Missing call preserved mask for calling convention");
3318
3319   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3320   // the function clobbers all registers. If an exception is thrown, the runtime
3321   // will not restore CSRs.
3322   // FIXME: Model this more precisely so that we can register allocate across
3323   // the normal edge and spill and fill across the exceptional edge.
3324   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3325     const Function *CallerFn = MF.getFunction();
3326     EHPersonality Pers =
3327         CallerFn->hasPersonalityFn()
3328             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3329             : EHPersonality::Unknown;
3330     if (isMSVCEHPersonality(Pers))
3331       Mask = RegInfo->getNoPreservedMask();
3332   }
3333
3334   Ops.push_back(DAG.getRegisterMask(Mask));
3335
3336   if (InFlag.getNode())
3337     Ops.push_back(InFlag);
3338
3339   if (isTailCall) {
3340     // We used to do:
3341     //// If this is the first return lowered for this function, add the regs
3342     //// to the liveout set for the function.
3343     // This isn't right, although it's probably harmless on x86; liveouts
3344     // should be computed from returns not tail calls.  Consider a void
3345     // function making a tail call to a function returning int.
3346     MF.getFrameInfo()->setHasTailCall();
3347     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3348   }
3349
3350   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3351   InFlag = Chain.getValue(1);
3352
3353   // Create the CALLSEQ_END node.
3354   unsigned NumBytesForCalleeToPop;
3355   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3356                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3357     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3358   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3359            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3360            SR == StackStructReturn)
3361     // If this is a call to a struct-return function, the callee
3362     // pops the hidden struct pointer, so we have to push it back.
3363     // This is common for Darwin/X86, Linux & Mingw32 targets.
3364     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3365     NumBytesForCalleeToPop = 4;
3366   else
3367     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3368
3369   // Returns a flag for retval copy to use.
3370   if (!IsSibcall) {
3371     Chain = DAG.getCALLSEQ_END(Chain,
3372                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3373                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3374                                                      true),
3375                                InFlag, dl);
3376     InFlag = Chain.getValue(1);
3377   }
3378
3379   // Handle result values, copying them out of physregs into vregs that we
3380   // return.
3381   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3382                          Ins, dl, DAG, InVals);
3383 }
3384
3385 //===----------------------------------------------------------------------===//
3386 //                Fast Calling Convention (tail call) implementation
3387 //===----------------------------------------------------------------------===//
3388
3389 //  Like std call, callee cleans arguments, convention except that ECX is
3390 //  reserved for storing the tail called function address. Only 2 registers are
3391 //  free for argument passing (inreg). Tail call optimization is performed
3392 //  provided:
3393 //                * tailcallopt is enabled
3394 //                * caller/callee are fastcc
3395 //  On X86_64 architecture with GOT-style position independent code only local
3396 //  (within module) calls are supported at the moment.
3397 //  To keep the stack aligned according to platform abi the function
3398 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3399 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3400 //  If a tail called function callee has more arguments than the caller the
3401 //  caller needs to make sure that there is room to move the RETADDR to. This is
3402 //  achieved by reserving an area the size of the argument delta right after the
3403 //  original RETADDR, but before the saved framepointer or the spilled registers
3404 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3405 //  stack layout:
3406 //    arg1
3407 //    arg2
3408 //    RETADDR
3409 //    [ new RETADDR
3410 //      move area ]
3411 //    (possible EBP)
3412 //    ESI
3413 //    EDI
3414 //    local1 ..
3415
3416 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3417 /// requirement.
3418 unsigned
3419 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3420                                                SelectionDAG& DAG) const {
3421   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3422   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3423   unsigned StackAlignment = TFI.getStackAlignment();
3424   uint64_t AlignMask = StackAlignment - 1;
3425   int64_t Offset = StackSize;
3426   unsigned SlotSize = RegInfo->getSlotSize();
3427   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3428     // Number smaller than 12 so just add the difference.
3429     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3430   } else {
3431     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3432     Offset = ((~AlignMask) & Offset) + StackAlignment +
3433       (StackAlignment-SlotSize);
3434   }
3435   return Offset;
3436 }
3437
3438 /// Return true if the given stack call argument is already available in the
3439 /// same position (relatively) of the caller's incoming argument stack.
3440 static
3441 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3442                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3443                          const X86InstrInfo *TII) {
3444   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3445   int FI = INT_MAX;
3446   if (Arg.getOpcode() == ISD::CopyFromReg) {
3447     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3448     if (!TargetRegisterInfo::isVirtualRegister(VR))
3449       return false;
3450     MachineInstr *Def = MRI->getVRegDef(VR);
3451     if (!Def)
3452       return false;
3453     if (!Flags.isByVal()) {
3454       if (!TII->isLoadFromStackSlot(Def, FI))
3455         return false;
3456     } else {
3457       unsigned Opcode = Def->getOpcode();
3458       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3459            Opcode == X86::LEA64_32r) &&
3460           Def->getOperand(1).isFI()) {
3461         FI = Def->getOperand(1).getIndex();
3462         Bytes = Flags.getByValSize();
3463       } else
3464         return false;
3465     }
3466   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3467     if (Flags.isByVal())
3468       // ByVal argument is passed in as a pointer but it's now being
3469       // dereferenced. e.g.
3470       // define @foo(%struct.X* %A) {
3471       //   tail call @bar(%struct.X* byval %A)
3472       // }
3473       return false;
3474     SDValue Ptr = Ld->getBasePtr();
3475     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3476     if (!FINode)
3477       return false;
3478     FI = FINode->getIndex();
3479   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3480     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3481     FI = FINode->getIndex();
3482     Bytes = Flags.getByValSize();
3483   } else
3484     return false;
3485
3486   assert(FI != INT_MAX);
3487   if (!MFI->isFixedObjectIndex(FI))
3488     return false;
3489   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3490 }
3491
3492 /// Check whether the call is eligible for tail call optimization. Targets
3493 /// that want to do tail call optimization should implement this function.
3494 bool
3495 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3496                                                      CallingConv::ID CalleeCC,
3497                                                      bool isVarArg,
3498                                                      bool isCalleeStructRet,
3499                                                      bool isCallerStructRet,
3500                                                      Type *RetTy,
3501                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3502                                     const SmallVectorImpl<SDValue> &OutVals,
3503                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3504                                                      SelectionDAG &DAG) const {
3505   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3506     return false;
3507
3508   // If -tailcallopt is specified, make fastcc functions tail-callable.
3509   const MachineFunction &MF = DAG.getMachineFunction();
3510   const Function *CallerF = MF.getFunction();
3511
3512   // If the function return type is x86_fp80 and the callee return type is not,
3513   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3514   // perform a tailcall optimization here.
3515   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3516     return false;
3517
3518   CallingConv::ID CallerCC = CallerF->getCallingConv();
3519   bool CCMatch = CallerCC == CalleeCC;
3520   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3521   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3522
3523   // Win64 functions have extra shadow space for argument homing. Don't do the
3524   // sibcall if the caller and callee have mismatched expectations for this
3525   // space.
3526   if (IsCalleeWin64 != IsCallerWin64)
3527     return false;
3528
3529   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3530     if (IsTailCallConvention(CalleeCC) && CCMatch)
3531       return true;
3532     return false;
3533   }
3534
3535   // Look for obvious safe cases to perform tail call optimization that do not
3536   // require ABI changes. This is what gcc calls sibcall.
3537
3538   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3539   // emit a special epilogue.
3540   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3541   if (RegInfo->needsStackRealignment(MF))
3542     return false;
3543
3544   // Also avoid sibcall optimization if either caller or callee uses struct
3545   // return semantics.
3546   if (isCalleeStructRet || isCallerStructRet)
3547     return false;
3548
3549   // An stdcall/thiscall caller is expected to clean up its arguments; the
3550   // callee isn't going to do that.
3551   // FIXME: this is more restrictive than needed. We could produce a tailcall
3552   // when the stack adjustment matches. For example, with a thiscall that takes
3553   // only one argument.
3554   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3555                    CallerCC == CallingConv::X86_ThisCall))
3556     return false;
3557
3558   // Do not sibcall optimize vararg calls unless all arguments are passed via
3559   // registers.
3560   if (isVarArg && !Outs.empty()) {
3561
3562     // Optimizing for varargs on Win64 is unlikely to be safe without
3563     // additional testing.
3564     if (IsCalleeWin64 || IsCallerWin64)
3565       return false;
3566
3567     SmallVector<CCValAssign, 16> ArgLocs;
3568     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3569                    *DAG.getContext());
3570
3571     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3572     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3573       if (!ArgLocs[i].isRegLoc())
3574         return false;
3575   }
3576
3577   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3578   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3579   // this into a sibcall.
3580   bool Unused = false;
3581   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3582     if (!Ins[i].Used) {
3583       Unused = true;
3584       break;
3585     }
3586   }
3587   if (Unused) {
3588     SmallVector<CCValAssign, 16> RVLocs;
3589     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3590                    *DAG.getContext());
3591     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3592     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3593       CCValAssign &VA = RVLocs[i];
3594       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3595         return false;
3596     }
3597   }
3598
3599   // If the calling conventions do not match, then we'd better make sure the
3600   // results are returned in the same way as what the caller expects.
3601   if (!CCMatch) {
3602     SmallVector<CCValAssign, 16> RVLocs1;
3603     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3604                     *DAG.getContext());
3605     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3606
3607     SmallVector<CCValAssign, 16> RVLocs2;
3608     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3609                     *DAG.getContext());
3610     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3611
3612     if (RVLocs1.size() != RVLocs2.size())
3613       return false;
3614     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3615       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3616         return false;
3617       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3618         return false;
3619       if (RVLocs1[i].isRegLoc()) {
3620         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3621           return false;
3622       } else {
3623         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3624           return false;
3625       }
3626     }
3627   }
3628
3629   // If the callee takes no arguments then go on to check the results of the
3630   // call.
3631   if (!Outs.empty()) {
3632     // Check if stack adjustment is needed. For now, do not do this if any
3633     // argument is passed on the stack.
3634     SmallVector<CCValAssign, 16> ArgLocs;
3635     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3636                    *DAG.getContext());
3637
3638     // Allocate shadow area for Win64
3639     if (IsCalleeWin64)
3640       CCInfo.AllocateStack(32, 8);
3641
3642     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3643     if (CCInfo.getNextStackOffset()) {
3644       MachineFunction &MF = DAG.getMachineFunction();
3645       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3646         return false;
3647
3648       // Check if the arguments are already laid out in the right way as
3649       // the caller's fixed stack objects.
3650       MachineFrameInfo *MFI = MF.getFrameInfo();
3651       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3652       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3653       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3654         CCValAssign &VA = ArgLocs[i];
3655         SDValue Arg = OutVals[i];
3656         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3657         if (VA.getLocInfo() == CCValAssign::Indirect)
3658           return false;
3659         if (!VA.isRegLoc()) {
3660           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3661                                    MFI, MRI, TII))
3662             return false;
3663         }
3664       }
3665     }
3666
3667     // If the tailcall address may be in a register, then make sure it's
3668     // possible to register allocate for it. In 32-bit, the call address can
3669     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3670     // callee-saved registers are restored. These happen to be the same
3671     // registers used to pass 'inreg' arguments so watch out for those.
3672     if (!Subtarget->is64Bit() &&
3673         ((!isa<GlobalAddressSDNode>(Callee) &&
3674           !isa<ExternalSymbolSDNode>(Callee)) ||
3675          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3676       unsigned NumInRegs = 0;
3677       // In PIC we need an extra register to formulate the address computation
3678       // for the callee.
3679       unsigned MaxInRegs =
3680         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3681
3682       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3683         CCValAssign &VA = ArgLocs[i];
3684         if (!VA.isRegLoc())
3685           continue;
3686         unsigned Reg = VA.getLocReg();
3687         switch (Reg) {
3688         default: break;
3689         case X86::EAX: case X86::EDX: case X86::ECX:
3690           if (++NumInRegs == MaxInRegs)
3691             return false;
3692           break;
3693         }
3694       }
3695     }
3696   }
3697
3698   return true;
3699 }
3700
3701 FastISel *
3702 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3703                                   const TargetLibraryInfo *libInfo) const {
3704   return X86::createFastISel(funcInfo, libInfo);
3705 }
3706
3707 //===----------------------------------------------------------------------===//
3708 //                           Other Lowering Hooks
3709 //===----------------------------------------------------------------------===//
3710
3711 static bool MayFoldLoad(SDValue Op) {
3712   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3713 }
3714
3715 static bool MayFoldIntoStore(SDValue Op) {
3716   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3717 }
3718
3719 static bool isTargetShuffle(unsigned Opcode) {
3720   switch(Opcode) {
3721   default: return false;
3722   case X86ISD::BLENDI:
3723   case X86ISD::PSHUFB:
3724   case X86ISD::PSHUFD:
3725   case X86ISD::PSHUFHW:
3726   case X86ISD::PSHUFLW:
3727   case X86ISD::SHUFP:
3728   case X86ISD::PALIGNR:
3729   case X86ISD::MOVLHPS:
3730   case X86ISD::MOVLHPD:
3731   case X86ISD::MOVHLPS:
3732   case X86ISD::MOVLPS:
3733   case X86ISD::MOVLPD:
3734   case X86ISD::MOVSHDUP:
3735   case X86ISD::MOVSLDUP:
3736   case X86ISD::MOVDDUP:
3737   case X86ISD::MOVSS:
3738   case X86ISD::MOVSD:
3739   case X86ISD::UNPCKL:
3740   case X86ISD::UNPCKH:
3741   case X86ISD::VPERMILPI:
3742   case X86ISD::VPERM2X128:
3743   case X86ISD::VPERMI:
3744     return true;
3745   }
3746 }
3747
3748 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3749                                     SDValue V1, unsigned TargetMask,
3750                                     SelectionDAG &DAG) {
3751   switch(Opc) {
3752   default: llvm_unreachable("Unknown x86 shuffle node");
3753   case X86ISD::PSHUFD:
3754   case X86ISD::PSHUFHW:
3755   case X86ISD::PSHUFLW:
3756   case X86ISD::VPERMILPI:
3757   case X86ISD::VPERMI:
3758     return DAG.getNode(Opc, dl, VT, V1,
3759                        DAG.getConstant(TargetMask, dl, MVT::i8));
3760   }
3761 }
3762
3763 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3764                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3765   switch(Opc) {
3766   default: llvm_unreachable("Unknown x86 shuffle node");
3767   case X86ISD::MOVLHPS:
3768   case X86ISD::MOVLHPD:
3769   case X86ISD::MOVHLPS:
3770   case X86ISD::MOVLPS:
3771   case X86ISD::MOVLPD:
3772   case X86ISD::MOVSS:
3773   case X86ISD::MOVSD:
3774   case X86ISD::UNPCKL:
3775   case X86ISD::UNPCKH:
3776     return DAG.getNode(Opc, dl, VT, V1, V2);
3777   }
3778 }
3779
3780 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3781   MachineFunction &MF = DAG.getMachineFunction();
3782   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3783   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3784   int ReturnAddrIndex = FuncInfo->getRAIndex();
3785
3786   if (ReturnAddrIndex == 0) {
3787     // Set up a frame object for the return address.
3788     unsigned SlotSize = RegInfo->getSlotSize();
3789     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3790                                                            -(int64_t)SlotSize,
3791                                                            false);
3792     FuncInfo->setRAIndex(ReturnAddrIndex);
3793   }
3794
3795   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3796 }
3797
3798 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3799                                        bool hasSymbolicDisplacement) {
3800   // Offset should fit into 32 bit immediate field.
3801   if (!isInt<32>(Offset))
3802     return false;
3803
3804   // If we don't have a symbolic displacement - we don't have any extra
3805   // restrictions.
3806   if (!hasSymbolicDisplacement)
3807     return true;
3808
3809   // FIXME: Some tweaks might be needed for medium code model.
3810   if (M != CodeModel::Small && M != CodeModel::Kernel)
3811     return false;
3812
3813   // For small code model we assume that latest object is 16MB before end of 31
3814   // bits boundary. We may also accept pretty large negative constants knowing
3815   // that all objects are in the positive half of address space.
3816   if (M == CodeModel::Small && Offset < 16*1024*1024)
3817     return true;
3818
3819   // For kernel code model we know that all object resist in the negative half
3820   // of 32bits address space. We may not accept negative offsets, since they may
3821   // be just off and we may accept pretty large positive ones.
3822   if (M == CodeModel::Kernel && Offset >= 0)
3823     return true;
3824
3825   return false;
3826 }
3827
3828 /// Determines whether the callee is required to pop its own arguments.
3829 /// Callee pop is necessary to support tail calls.
3830 bool X86::isCalleePop(CallingConv::ID CallingConv,
3831                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3832   switch (CallingConv) {
3833   default:
3834     return false;
3835   case CallingConv::X86_StdCall:
3836   case CallingConv::X86_FastCall:
3837   case CallingConv::X86_ThisCall:
3838     return !is64Bit;
3839   case CallingConv::Fast:
3840   case CallingConv::GHC:
3841   case CallingConv::HiPE:
3842     if (IsVarArg)
3843       return false;
3844     return TailCallOpt;
3845   }
3846 }
3847
3848 /// \brief Return true if the condition is an unsigned comparison operation.
3849 static bool isX86CCUnsigned(unsigned X86CC) {
3850   switch (X86CC) {
3851   default: llvm_unreachable("Invalid integer condition!");
3852   case X86::COND_E:     return true;
3853   case X86::COND_G:     return false;
3854   case X86::COND_GE:    return false;
3855   case X86::COND_L:     return false;
3856   case X86::COND_LE:    return false;
3857   case X86::COND_NE:    return true;
3858   case X86::COND_B:     return true;
3859   case X86::COND_A:     return true;
3860   case X86::COND_BE:    return true;
3861   case X86::COND_AE:    return true;
3862   }
3863   llvm_unreachable("covered switch fell through?!");
3864 }
3865
3866 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3867 /// condition code, returning the condition code and the LHS/RHS of the
3868 /// comparison to make.
3869 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3870                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3871   if (!isFP) {
3872     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3873       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3874         // X > -1   -> X == 0, jump !sign.
3875         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3876         return X86::COND_NS;
3877       }
3878       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3879         // X < 0   -> X == 0, jump on sign.
3880         return X86::COND_S;
3881       }
3882       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3883         // X < 1   -> X <= 0
3884         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3885         return X86::COND_LE;
3886       }
3887     }
3888
3889     switch (SetCCOpcode) {
3890     default: llvm_unreachable("Invalid integer condition!");
3891     case ISD::SETEQ:  return X86::COND_E;
3892     case ISD::SETGT:  return X86::COND_G;
3893     case ISD::SETGE:  return X86::COND_GE;
3894     case ISD::SETLT:  return X86::COND_L;
3895     case ISD::SETLE:  return X86::COND_LE;
3896     case ISD::SETNE:  return X86::COND_NE;
3897     case ISD::SETULT: return X86::COND_B;
3898     case ISD::SETUGT: return X86::COND_A;
3899     case ISD::SETULE: return X86::COND_BE;
3900     case ISD::SETUGE: return X86::COND_AE;
3901     }
3902   }
3903
3904   // First determine if it is required or is profitable to flip the operands.
3905
3906   // If LHS is a foldable load, but RHS is not, flip the condition.
3907   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3908       !ISD::isNON_EXTLoad(RHS.getNode())) {
3909     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3910     std::swap(LHS, RHS);
3911   }
3912
3913   switch (SetCCOpcode) {
3914   default: break;
3915   case ISD::SETOLT:
3916   case ISD::SETOLE:
3917   case ISD::SETUGT:
3918   case ISD::SETUGE:
3919     std::swap(LHS, RHS);
3920     break;
3921   }
3922
3923   // On a floating point condition, the flags are set as follows:
3924   // ZF  PF  CF   op
3925   //  0 | 0 | 0 | X > Y
3926   //  0 | 0 | 1 | X < Y
3927   //  1 | 0 | 0 | X == Y
3928   //  1 | 1 | 1 | unordered
3929   switch (SetCCOpcode) {
3930   default: llvm_unreachable("Condcode should be pre-legalized away");
3931   case ISD::SETUEQ:
3932   case ISD::SETEQ:   return X86::COND_E;
3933   case ISD::SETOLT:              // flipped
3934   case ISD::SETOGT:
3935   case ISD::SETGT:   return X86::COND_A;
3936   case ISD::SETOLE:              // flipped
3937   case ISD::SETOGE:
3938   case ISD::SETGE:   return X86::COND_AE;
3939   case ISD::SETUGT:              // flipped
3940   case ISD::SETULT:
3941   case ISD::SETLT:   return X86::COND_B;
3942   case ISD::SETUGE:              // flipped
3943   case ISD::SETULE:
3944   case ISD::SETLE:   return X86::COND_BE;
3945   case ISD::SETONE:
3946   case ISD::SETNE:   return X86::COND_NE;
3947   case ISD::SETUO:   return X86::COND_P;
3948   case ISD::SETO:    return X86::COND_NP;
3949   case ISD::SETOEQ:
3950   case ISD::SETUNE:  return X86::COND_INVALID;
3951   }
3952 }
3953
3954 /// Is there a floating point cmov for the specific X86 condition code?
3955 /// Current x86 isa includes the following FP cmov instructions:
3956 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3957 static bool hasFPCMov(unsigned X86CC) {
3958   switch (X86CC) {
3959   default:
3960     return false;
3961   case X86::COND_B:
3962   case X86::COND_BE:
3963   case X86::COND_E:
3964   case X86::COND_P:
3965   case X86::COND_A:
3966   case X86::COND_AE:
3967   case X86::COND_NE:
3968   case X86::COND_NP:
3969     return true;
3970   }
3971 }
3972
3973 /// Returns true if the target can instruction select the
3974 /// specified FP immediate natively. If false, the legalizer will
3975 /// materialize the FP immediate as a load from a constant pool.
3976 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3977   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3978     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3979       return true;
3980   }
3981   return false;
3982 }
3983
3984 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3985                                               ISD::LoadExtType ExtTy,
3986                                               EVT NewVT) const {
3987   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3988   // relocation target a movq or addq instruction: don't let the load shrink.
3989   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3990   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3991     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3992       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3993   return true;
3994 }
3995
3996 /// \brief Returns true if it is beneficial to convert a load of a constant
3997 /// to just the constant itself.
3998 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3999                                                           Type *Ty) const {
4000   assert(Ty->isIntegerTy());
4001
4002   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4003   if (BitSize == 0 || BitSize > 64)
4004     return false;
4005   return true;
4006 }
4007
4008 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4009                                                 unsigned Index) const {
4010   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4011     return false;
4012
4013   return (Index == 0 || Index == ResVT.getVectorNumElements());
4014 }
4015
4016 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4017   // Speculate cttz only if we can directly use TZCNT.
4018   return Subtarget->hasBMI();
4019 }
4020
4021 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4022   // Speculate ctlz only if we can directly use LZCNT.
4023   return Subtarget->hasLZCNT();
4024 }
4025
4026 /// Return true if every element in Mask, beginning
4027 /// from position Pos and ending in Pos+Size is undef.
4028 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4029   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4030     if (0 <= Mask[i])
4031       return false;
4032   return true;
4033 }
4034
4035 /// Return true if Val is undef or if its value falls within the
4036 /// specified range (L, H].
4037 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4038   return (Val < 0) || (Val >= Low && Val < Hi);
4039 }
4040
4041 /// Val is either less than zero (undef) or equal to the specified value.
4042 static bool isUndefOrEqual(int Val, int CmpVal) {
4043   return (Val < 0 || Val == CmpVal);
4044 }
4045
4046 /// Return true if every element in Mask, beginning
4047 /// from position Pos and ending in Pos+Size, falls within the specified
4048 /// sequential range (Low, Low+Size]. or is undef.
4049 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4050                                        unsigned Pos, unsigned Size, int Low) {
4051   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4052     if (!isUndefOrEqual(Mask[i], Low))
4053       return false;
4054   return true;
4055 }
4056
4057 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4058 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4059 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4060   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4061   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4062     return false;
4063
4064   // The index should be aligned on a vecWidth-bit boundary.
4065   uint64_t Index =
4066     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4067
4068   MVT VT = N->getSimpleValueType(0);
4069   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4070   bool Result = (Index * ElSize) % vecWidth == 0;
4071
4072   return Result;
4073 }
4074
4075 /// Return true if the specified INSERT_SUBVECTOR
4076 /// operand specifies a subvector insert that is suitable for input to
4077 /// insertion of 128 or 256-bit subvectors
4078 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4079   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4080   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4081     return false;
4082   // The index should be aligned on a vecWidth-bit boundary.
4083   uint64_t Index =
4084     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4085
4086   MVT VT = N->getSimpleValueType(0);
4087   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4088   bool Result = (Index * ElSize) % vecWidth == 0;
4089
4090   return Result;
4091 }
4092
4093 bool X86::isVINSERT128Index(SDNode *N) {
4094   return isVINSERTIndex(N, 128);
4095 }
4096
4097 bool X86::isVINSERT256Index(SDNode *N) {
4098   return isVINSERTIndex(N, 256);
4099 }
4100
4101 bool X86::isVEXTRACT128Index(SDNode *N) {
4102   return isVEXTRACTIndex(N, 128);
4103 }
4104
4105 bool X86::isVEXTRACT256Index(SDNode *N) {
4106   return isVEXTRACTIndex(N, 256);
4107 }
4108
4109 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4110   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4111   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4112     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4113
4114   uint64_t Index =
4115     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4116
4117   MVT VecVT = N->getOperand(0).getSimpleValueType();
4118   MVT ElVT = VecVT.getVectorElementType();
4119
4120   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4121   return Index / NumElemsPerChunk;
4122 }
4123
4124 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4125   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4126   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4127     llvm_unreachable("Illegal insert subvector for VINSERT");
4128
4129   uint64_t Index =
4130     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4131
4132   MVT VecVT = N->getSimpleValueType(0);
4133   MVT ElVT = VecVT.getVectorElementType();
4134
4135   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4136   return Index / NumElemsPerChunk;
4137 }
4138
4139 /// Return the appropriate immediate to extract the specified
4140 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4141 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4142   return getExtractVEXTRACTImmediate(N, 128);
4143 }
4144
4145 /// Return the appropriate immediate to extract the specified
4146 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4147 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4148   return getExtractVEXTRACTImmediate(N, 256);
4149 }
4150
4151 /// Return the appropriate immediate to insert at the specified
4152 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4153 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4154   return getInsertVINSERTImmediate(N, 128);
4155 }
4156
4157 /// Return the appropriate immediate to insert at the specified
4158 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4159 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4160   return getInsertVINSERTImmediate(N, 256);
4161 }
4162
4163 /// Returns true if Elt is a constant integer zero
4164 static bool isZero(SDValue V) {
4165   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4166   return C && C->isNullValue();
4167 }
4168
4169 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4170 bool X86::isZeroNode(SDValue Elt) {
4171   if (isZero(Elt))
4172     return true;
4173   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4174     return CFP->getValueAPF().isPosZero();
4175   return false;
4176 }
4177
4178 /// Returns a vector of specified type with all zero elements.
4179 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4180                              SelectionDAG &DAG, SDLoc dl) {
4181   assert(VT.isVector() && "Expected a vector type");
4182
4183   // Always build SSE zero vectors as <4 x i32> bitcasted
4184   // to their dest type. This ensures they get CSE'd.
4185   SDValue Vec;
4186   if (VT.is128BitVector()) {  // SSE
4187     if (Subtarget->hasSSE2()) {  // SSE2
4188       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4189       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4190     } else { // SSE1
4191       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4192       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4193     }
4194   } else if (VT.is256BitVector()) { // AVX
4195     if (Subtarget->hasInt256()) { // AVX2
4196       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4197       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4198       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4199     } else {
4200       // 256-bit logic and arithmetic instructions in AVX are all
4201       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4202       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4203       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4204       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4205     }
4206   } else if (VT.is512BitVector()) { // AVX-512
4207       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4208       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4209                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4210       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4211   } else if (VT.getScalarType() == MVT::i1) {
4212
4213     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4214             && "Unexpected vector type");
4215     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4216             && "Unexpected vector type");
4217     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4218     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4219     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4220   } else
4221     llvm_unreachable("Unexpected vector type");
4222
4223   return DAG.getBitcast(VT, Vec);
4224 }
4225
4226 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4227                                 SelectionDAG &DAG, SDLoc dl,
4228                                 unsigned vectorWidth) {
4229   assert((vectorWidth == 128 || vectorWidth == 256) &&
4230          "Unsupported vector width");
4231   EVT VT = Vec.getValueType();
4232   EVT ElVT = VT.getVectorElementType();
4233   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4234   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4235                                   VT.getVectorNumElements()/Factor);
4236
4237   // Extract from UNDEF is UNDEF.
4238   if (Vec.getOpcode() == ISD::UNDEF)
4239     return DAG.getUNDEF(ResultVT);
4240
4241   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4242   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4243
4244   // This is the index of the first element of the vectorWidth-bit chunk
4245   // we want.
4246   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4247                                * ElemsPerChunk);
4248
4249   // If the input is a buildvector just emit a smaller one.
4250   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4251     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4252                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4253                                     ElemsPerChunk));
4254
4255   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4256   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4257 }
4258
4259 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4260 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4261 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4262 /// instructions or a simple subregister reference. Idx is an index in the
4263 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4264 /// lowering EXTRACT_VECTOR_ELT operations easier.
4265 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4266                                    SelectionDAG &DAG, SDLoc dl) {
4267   assert((Vec.getValueType().is256BitVector() ||
4268           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4269   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4270 }
4271
4272 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4273 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4274                                    SelectionDAG &DAG, SDLoc dl) {
4275   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4276   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4277 }
4278
4279 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4280                                unsigned IdxVal, SelectionDAG &DAG,
4281                                SDLoc dl, unsigned vectorWidth) {
4282   assert((vectorWidth == 128 || vectorWidth == 256) &&
4283          "Unsupported vector width");
4284   // Inserting UNDEF is Result
4285   if (Vec.getOpcode() == ISD::UNDEF)
4286     return Result;
4287   EVT VT = Vec.getValueType();
4288   EVT ElVT = VT.getVectorElementType();
4289   EVT ResultVT = Result.getValueType();
4290
4291   // Insert the relevant vectorWidth bits.
4292   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4293
4294   // This is the index of the first element of the vectorWidth-bit chunk
4295   // we want.
4296   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4297                                * ElemsPerChunk);
4298
4299   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4300   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4301 }
4302
4303 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4304 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4305 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4306 /// simple superregister reference.  Idx is an index in the 128 bits
4307 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4308 /// lowering INSERT_VECTOR_ELT operations easier.
4309 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4310                                   SelectionDAG &DAG, SDLoc dl) {
4311   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4312
4313   // For insertion into the zero index (low half) of a 256-bit vector, it is
4314   // more efficient to generate a blend with immediate instead of an insert*128.
4315   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4316   // extend the subvector to the size of the result vector. Make sure that
4317   // we are not recursing on that node by checking for undef here.
4318   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4319       Result.getOpcode() != ISD::UNDEF) {
4320     EVT ResultVT = Result.getValueType();
4321     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4322     SDValue Undef = DAG.getUNDEF(ResultVT);
4323     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4324                                  Vec, ZeroIndex);
4325
4326     // The blend instruction, and therefore its mask, depend on the data type.
4327     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4328     if (ScalarType.isFloatingPoint()) {
4329       // Choose either vblendps (float) or vblendpd (double).
4330       unsigned ScalarSize = ScalarType.getSizeInBits();
4331       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4332       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4333       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4334       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4335     }
4336
4337     const X86Subtarget &Subtarget =
4338     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4339
4340     // AVX2 is needed for 256-bit integer blend support.
4341     // Integers must be cast to 32-bit because there is only vpblendd;
4342     // vpblendw can't be used for this because it has a handicapped mask.
4343
4344     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4345     // is still more efficient than using the wrong domain vinsertf128 that
4346     // will be created by InsertSubVector().
4347     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4348
4349     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4350     Vec256 = DAG.getBitcast(CastVT, Vec256);
4351     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4352     return DAG.getBitcast(ResultVT, Vec256);
4353   }
4354
4355   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4356 }
4357
4358 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4359                                   SelectionDAG &DAG, SDLoc dl) {
4360   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4361   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4362 }
4363
4364 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4365 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4366 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4367 /// large BUILD_VECTORS.
4368 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4369                                    unsigned NumElems, SelectionDAG &DAG,
4370                                    SDLoc dl) {
4371   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4372   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4373 }
4374
4375 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4376                                    unsigned NumElems, SelectionDAG &DAG,
4377                                    SDLoc dl) {
4378   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4379   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4380 }
4381
4382 /// Returns a vector of specified type with all bits set.
4383 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4384 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4385 /// Then bitcast to their original type, ensuring they get CSE'd.
4386 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4387                              SDLoc dl) {
4388   assert(VT.isVector() && "Expected a vector type");
4389
4390   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4391   SDValue Vec;
4392   if (VT.is256BitVector()) {
4393     if (HasInt256) { // AVX2
4394       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4395       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4396     } else { // AVX
4397       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4398       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4399     }
4400   } else if (VT.is128BitVector()) {
4401     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4402   } else
4403     llvm_unreachable("Unexpected vector type");
4404
4405   return DAG.getBitcast(VT, Vec);
4406 }
4407
4408 /// Returns a vector_shuffle node for an unpackl operation.
4409 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4410                           SDValue V2) {
4411   unsigned NumElems = VT.getVectorNumElements();
4412   SmallVector<int, 8> Mask;
4413   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4414     Mask.push_back(i);
4415     Mask.push_back(i + NumElems);
4416   }
4417   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4418 }
4419
4420 /// Returns a vector_shuffle node for an unpackh operation.
4421 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4422                           SDValue V2) {
4423   unsigned NumElems = VT.getVectorNumElements();
4424   SmallVector<int, 8> Mask;
4425   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4426     Mask.push_back(i + Half);
4427     Mask.push_back(i + NumElems + Half);
4428   }
4429   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4430 }
4431
4432 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4433 /// This produces a shuffle where the low element of V2 is swizzled into the
4434 /// zero/undef vector, landing at element Idx.
4435 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4436 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4437                                            bool IsZero,
4438                                            const X86Subtarget *Subtarget,
4439                                            SelectionDAG &DAG) {
4440   MVT VT = V2.getSimpleValueType();
4441   SDValue V1 = IsZero
4442     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4443   unsigned NumElems = VT.getVectorNumElements();
4444   SmallVector<int, 16> MaskVec;
4445   for (unsigned i = 0; i != NumElems; ++i)
4446     // If this is the insertion idx, put the low elt of V2 here.
4447     MaskVec.push_back(i == Idx ? NumElems : i);
4448   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4449 }
4450
4451 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4452 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4453 /// uses one source. Note that this will set IsUnary for shuffles which use a
4454 /// single input multiple times, and in those cases it will
4455 /// adjust the mask to only have indices within that single input.
4456 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4457 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4458                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4459   unsigned NumElems = VT.getVectorNumElements();
4460   SDValue ImmN;
4461
4462   IsUnary = false;
4463   bool IsFakeUnary = false;
4464   switch(N->getOpcode()) {
4465   case X86ISD::BLENDI:
4466     ImmN = N->getOperand(N->getNumOperands()-1);
4467     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4468     break;
4469   case X86ISD::SHUFP:
4470     ImmN = N->getOperand(N->getNumOperands()-1);
4471     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4472     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4473     break;
4474   case X86ISD::UNPCKH:
4475     DecodeUNPCKHMask(VT, Mask);
4476     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4477     break;
4478   case X86ISD::UNPCKL:
4479     DecodeUNPCKLMask(VT, Mask);
4480     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4481     break;
4482   case X86ISD::MOVHLPS:
4483     DecodeMOVHLPSMask(NumElems, Mask);
4484     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4485     break;
4486   case X86ISD::MOVLHPS:
4487     DecodeMOVLHPSMask(NumElems, Mask);
4488     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4489     break;
4490   case X86ISD::PALIGNR:
4491     ImmN = N->getOperand(N->getNumOperands()-1);
4492     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4493     break;
4494   case X86ISD::PSHUFD:
4495   case X86ISD::VPERMILPI:
4496     ImmN = N->getOperand(N->getNumOperands()-1);
4497     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4498     IsUnary = true;
4499     break;
4500   case X86ISD::PSHUFHW:
4501     ImmN = N->getOperand(N->getNumOperands()-1);
4502     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4503     IsUnary = true;
4504     break;
4505   case X86ISD::PSHUFLW:
4506     ImmN = N->getOperand(N->getNumOperands()-1);
4507     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4508     IsUnary = true;
4509     break;
4510   case X86ISD::PSHUFB: {
4511     IsUnary = true;
4512     SDValue MaskNode = N->getOperand(1);
4513     while (MaskNode->getOpcode() == ISD::BITCAST)
4514       MaskNode = MaskNode->getOperand(0);
4515
4516     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4517       // If we have a build-vector, then things are easy.
4518       EVT VT = MaskNode.getValueType();
4519       assert(VT.isVector() &&
4520              "Can't produce a non-vector with a build_vector!");
4521       if (!VT.isInteger())
4522         return false;
4523
4524       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4525
4526       SmallVector<uint64_t, 32> RawMask;
4527       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4528         SDValue Op = MaskNode->getOperand(i);
4529         if (Op->getOpcode() == ISD::UNDEF) {
4530           RawMask.push_back((uint64_t)SM_SentinelUndef);
4531           continue;
4532         }
4533         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4534         if (!CN)
4535           return false;
4536         APInt MaskElement = CN->getAPIntValue();
4537
4538         // We now have to decode the element which could be any integer size and
4539         // extract each byte of it.
4540         for (int j = 0; j < NumBytesPerElement; ++j) {
4541           // Note that this is x86 and so always little endian: the low byte is
4542           // the first byte of the mask.
4543           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4544           MaskElement = MaskElement.lshr(8);
4545         }
4546       }
4547       DecodePSHUFBMask(RawMask, Mask);
4548       break;
4549     }
4550
4551     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4552     if (!MaskLoad)
4553       return false;
4554
4555     SDValue Ptr = MaskLoad->getBasePtr();
4556     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4557         Ptr->getOpcode() == X86ISD::WrapperRIP)
4558       Ptr = Ptr->getOperand(0);
4559
4560     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4561     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4562       return false;
4563
4564     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4565       DecodePSHUFBMask(C, Mask);
4566       if (Mask.empty())
4567         return false;
4568       break;
4569     }
4570
4571     return false;
4572   }
4573   case X86ISD::VPERMI:
4574     ImmN = N->getOperand(N->getNumOperands()-1);
4575     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4576     IsUnary = true;
4577     break;
4578   case X86ISD::MOVSS:
4579   case X86ISD::MOVSD:
4580     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4581     break;
4582   case X86ISD::VPERM2X128:
4583     ImmN = N->getOperand(N->getNumOperands()-1);
4584     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4585     if (Mask.empty()) return false;
4586     // Mask only contains negative index if an element is zero.
4587     if (std::any_of(Mask.begin(), Mask.end(),
4588                     [](int M){ return M == SM_SentinelZero; }))
4589       return false;
4590     break;
4591   case X86ISD::MOVSLDUP:
4592     DecodeMOVSLDUPMask(VT, Mask);
4593     IsUnary = true;
4594     break;
4595   case X86ISD::MOVSHDUP:
4596     DecodeMOVSHDUPMask(VT, Mask);
4597     IsUnary = true;
4598     break;
4599   case X86ISD::MOVDDUP:
4600     DecodeMOVDDUPMask(VT, Mask);
4601     IsUnary = true;
4602     break;
4603   case X86ISD::MOVLHPD:
4604   case X86ISD::MOVLPD:
4605   case X86ISD::MOVLPS:
4606     // Not yet implemented
4607     return false;
4608   default: llvm_unreachable("unknown target shuffle node");
4609   }
4610
4611   // If we have a fake unary shuffle, the shuffle mask is spread across two
4612   // inputs that are actually the same node. Re-map the mask to always point
4613   // into the first input.
4614   if (IsFakeUnary)
4615     for (int &M : Mask)
4616       if (M >= (int)Mask.size())
4617         M -= Mask.size();
4618
4619   return true;
4620 }
4621
4622 /// Returns the scalar element that will make up the ith
4623 /// element of the result of the vector shuffle.
4624 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4625                                    unsigned Depth) {
4626   if (Depth == 6)
4627     return SDValue();  // Limit search depth.
4628
4629   SDValue V = SDValue(N, 0);
4630   EVT VT = V.getValueType();
4631   unsigned Opcode = V.getOpcode();
4632
4633   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4634   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4635     int Elt = SV->getMaskElt(Index);
4636
4637     if (Elt < 0)
4638       return DAG.getUNDEF(VT.getVectorElementType());
4639
4640     unsigned NumElems = VT.getVectorNumElements();
4641     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4642                                          : SV->getOperand(1);
4643     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4644   }
4645
4646   // Recurse into target specific vector shuffles to find scalars.
4647   if (isTargetShuffle(Opcode)) {
4648     MVT ShufVT = V.getSimpleValueType();
4649     unsigned NumElems = ShufVT.getVectorNumElements();
4650     SmallVector<int, 16> ShuffleMask;
4651     bool IsUnary;
4652
4653     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4654       return SDValue();
4655
4656     int Elt = ShuffleMask[Index];
4657     if (Elt < 0)
4658       return DAG.getUNDEF(ShufVT.getVectorElementType());
4659
4660     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4661                                          : N->getOperand(1);
4662     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4663                                Depth+1);
4664   }
4665
4666   // Actual nodes that may contain scalar elements
4667   if (Opcode == ISD::BITCAST) {
4668     V = V.getOperand(0);
4669     EVT SrcVT = V.getValueType();
4670     unsigned NumElems = VT.getVectorNumElements();
4671
4672     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4673       return SDValue();
4674   }
4675
4676   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4677     return (Index == 0) ? V.getOperand(0)
4678                         : DAG.getUNDEF(VT.getVectorElementType());
4679
4680   if (V.getOpcode() == ISD::BUILD_VECTOR)
4681     return V.getOperand(Index);
4682
4683   return SDValue();
4684 }
4685
4686 /// Custom lower build_vector of v16i8.
4687 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4688                                        unsigned NumNonZero, unsigned NumZero,
4689                                        SelectionDAG &DAG,
4690                                        const X86Subtarget* Subtarget,
4691                                        const TargetLowering &TLI) {
4692   if (NumNonZero > 8)
4693     return SDValue();
4694
4695   SDLoc dl(Op);
4696   SDValue V;
4697   bool First = true;
4698
4699   // SSE4.1 - use PINSRB to insert each byte directly.
4700   if (Subtarget->hasSSE41()) {
4701     for (unsigned i = 0; i < 16; ++i) {
4702       bool isNonZero = (NonZeros & (1 << i)) != 0;
4703       if (isNonZero) {
4704         if (First) {
4705           if (NumZero)
4706             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4707           else
4708             V = DAG.getUNDEF(MVT::v16i8);
4709           First = false;
4710         }
4711         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4712                         MVT::v16i8, V, Op.getOperand(i),
4713                         DAG.getIntPtrConstant(i, dl));
4714       }
4715     }
4716
4717     return V;
4718   }
4719
4720   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4721   for (unsigned i = 0; i < 16; ++i) {
4722     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4723     if (ThisIsNonZero && First) {
4724       if (NumZero)
4725         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4726       else
4727         V = DAG.getUNDEF(MVT::v8i16);
4728       First = false;
4729     }
4730
4731     if ((i & 1) != 0) {
4732       SDValue ThisElt, LastElt;
4733       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4734       if (LastIsNonZero) {
4735         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4736                               MVT::i16, Op.getOperand(i-1));
4737       }
4738       if (ThisIsNonZero) {
4739         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4740         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4741                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4742         if (LastIsNonZero)
4743           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4744       } else
4745         ThisElt = LastElt;
4746
4747       if (ThisElt.getNode())
4748         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4749                         DAG.getIntPtrConstant(i/2, dl));
4750     }
4751   }
4752
4753   return DAG.getBitcast(MVT::v16i8, V);
4754 }
4755
4756 /// Custom lower build_vector of v8i16.
4757 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4758                                      unsigned NumNonZero, unsigned NumZero,
4759                                      SelectionDAG &DAG,
4760                                      const X86Subtarget* Subtarget,
4761                                      const TargetLowering &TLI) {
4762   if (NumNonZero > 4)
4763     return SDValue();
4764
4765   SDLoc dl(Op);
4766   SDValue V;
4767   bool First = true;
4768   for (unsigned i = 0; i < 8; ++i) {
4769     bool isNonZero = (NonZeros & (1 << i)) != 0;
4770     if (isNonZero) {
4771       if (First) {
4772         if (NumZero)
4773           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4774         else
4775           V = DAG.getUNDEF(MVT::v8i16);
4776         First = false;
4777       }
4778       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4779                       MVT::v8i16, V, Op.getOperand(i),
4780                       DAG.getIntPtrConstant(i, dl));
4781     }
4782   }
4783
4784   return V;
4785 }
4786
4787 /// Custom lower build_vector of v4i32 or v4f32.
4788 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4789                                      const X86Subtarget *Subtarget,
4790                                      const TargetLowering &TLI) {
4791   // Find all zeroable elements.
4792   std::bitset<4> Zeroable;
4793   for (int i=0; i < 4; ++i) {
4794     SDValue Elt = Op->getOperand(i);
4795     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4796   }
4797   assert(Zeroable.size() - Zeroable.count() > 1 &&
4798          "We expect at least two non-zero elements!");
4799
4800   // We only know how to deal with build_vector nodes where elements are either
4801   // zeroable or extract_vector_elt with constant index.
4802   SDValue FirstNonZero;
4803   unsigned FirstNonZeroIdx;
4804   for (unsigned i=0; i < 4; ++i) {
4805     if (Zeroable[i])
4806       continue;
4807     SDValue Elt = Op->getOperand(i);
4808     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4809         !isa<ConstantSDNode>(Elt.getOperand(1)))
4810       return SDValue();
4811     // Make sure that this node is extracting from a 128-bit vector.
4812     MVT VT = Elt.getOperand(0).getSimpleValueType();
4813     if (!VT.is128BitVector())
4814       return SDValue();
4815     if (!FirstNonZero.getNode()) {
4816       FirstNonZero = Elt;
4817       FirstNonZeroIdx = i;
4818     }
4819   }
4820
4821   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4822   SDValue V1 = FirstNonZero.getOperand(0);
4823   MVT VT = V1.getSimpleValueType();
4824
4825   // See if this build_vector can be lowered as a blend with zero.
4826   SDValue Elt;
4827   unsigned EltMaskIdx, EltIdx;
4828   int Mask[4];
4829   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4830     if (Zeroable[EltIdx]) {
4831       // The zero vector will be on the right hand side.
4832       Mask[EltIdx] = EltIdx+4;
4833       continue;
4834     }
4835
4836     Elt = Op->getOperand(EltIdx);
4837     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4838     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4839     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4840       break;
4841     Mask[EltIdx] = EltIdx;
4842   }
4843
4844   if (EltIdx == 4) {
4845     // Let the shuffle legalizer deal with blend operations.
4846     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4847     if (V1.getSimpleValueType() != VT)
4848       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4849     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4850   }
4851
4852   // See if we can lower this build_vector to a INSERTPS.
4853   if (!Subtarget->hasSSE41())
4854     return SDValue();
4855
4856   SDValue V2 = Elt.getOperand(0);
4857   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4858     V1 = SDValue();
4859
4860   bool CanFold = true;
4861   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4862     if (Zeroable[i])
4863       continue;
4864
4865     SDValue Current = Op->getOperand(i);
4866     SDValue SrcVector = Current->getOperand(0);
4867     if (!V1.getNode())
4868       V1 = SrcVector;
4869     CanFold = SrcVector == V1 &&
4870       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4871   }
4872
4873   if (!CanFold)
4874     return SDValue();
4875
4876   assert(V1.getNode() && "Expected at least two non-zero elements!");
4877   if (V1.getSimpleValueType() != MVT::v4f32)
4878     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4879   if (V2.getSimpleValueType() != MVT::v4f32)
4880     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4881
4882   // Ok, we can emit an INSERTPS instruction.
4883   unsigned ZMask = Zeroable.to_ulong();
4884
4885   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4886   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4887   SDLoc DL(Op);
4888   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4889                                DAG.getIntPtrConstant(InsertPSMask, DL));
4890   return DAG.getBitcast(VT, Result);
4891 }
4892
4893 /// Return a vector logical shift node.
4894 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4895                          unsigned NumBits, SelectionDAG &DAG,
4896                          const TargetLowering &TLI, SDLoc dl) {
4897   assert(VT.is128BitVector() && "Unknown type for VShift");
4898   MVT ShVT = MVT::v2i64;
4899   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4900   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4901   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4902   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4903   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4904   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4905 }
4906
4907 static SDValue
4908 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4909
4910   // Check if the scalar load can be widened into a vector load. And if
4911   // the address is "base + cst" see if the cst can be "absorbed" into
4912   // the shuffle mask.
4913   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4914     SDValue Ptr = LD->getBasePtr();
4915     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4916       return SDValue();
4917     EVT PVT = LD->getValueType(0);
4918     if (PVT != MVT::i32 && PVT != MVT::f32)
4919       return SDValue();
4920
4921     int FI = -1;
4922     int64_t Offset = 0;
4923     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4924       FI = FINode->getIndex();
4925       Offset = 0;
4926     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4927                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4928       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4929       Offset = Ptr.getConstantOperandVal(1);
4930       Ptr = Ptr.getOperand(0);
4931     } else {
4932       return SDValue();
4933     }
4934
4935     // FIXME: 256-bit vector instructions don't require a strict alignment,
4936     // improve this code to support it better.
4937     unsigned RequiredAlign = VT.getSizeInBits()/8;
4938     SDValue Chain = LD->getChain();
4939     // Make sure the stack object alignment is at least 16 or 32.
4940     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4941     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4942       if (MFI->isFixedObjectIndex(FI)) {
4943         // Can't change the alignment. FIXME: It's possible to compute
4944         // the exact stack offset and reference FI + adjust offset instead.
4945         // If someone *really* cares about this. That's the way to implement it.
4946         return SDValue();
4947       } else {
4948         MFI->setObjectAlignment(FI, RequiredAlign);
4949       }
4950     }
4951
4952     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4953     // Ptr + (Offset & ~15).
4954     if (Offset < 0)
4955       return SDValue();
4956     if ((Offset % RequiredAlign) & 3)
4957       return SDValue();
4958     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4959     if (StartOffset) {
4960       SDLoc DL(Ptr);
4961       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4962                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4963     }
4964
4965     int EltNo = (Offset - StartOffset) >> 2;
4966     unsigned NumElems = VT.getVectorNumElements();
4967
4968     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4969     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4970                              LD->getPointerInfo().getWithOffset(StartOffset),
4971                              false, false, false, 0);
4972
4973     SmallVector<int, 8> Mask(NumElems, EltNo);
4974
4975     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4976   }
4977
4978   return SDValue();
4979 }
4980
4981 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4982 /// elements can be replaced by a single large load which has the same value as
4983 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4984 ///
4985 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4986 ///
4987 /// FIXME: we'd also like to handle the case where the last elements are zero
4988 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4989 /// There's even a handy isZeroNode for that purpose.
4990 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4991                                         SDLoc &DL, SelectionDAG &DAG,
4992                                         bool isAfterLegalize) {
4993   unsigned NumElems = Elts.size();
4994
4995   LoadSDNode *LDBase = nullptr;
4996   unsigned LastLoadedElt = -1U;
4997
4998   // For each element in the initializer, see if we've found a load or an undef.
4999   // If we don't find an initial load element, or later load elements are
5000   // non-consecutive, bail out.
5001   for (unsigned i = 0; i < NumElems; ++i) {
5002     SDValue Elt = Elts[i];
5003     // Look through a bitcast.
5004     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5005       Elt = Elt.getOperand(0);
5006     if (!Elt.getNode() ||
5007         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5008       return SDValue();
5009     if (!LDBase) {
5010       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5011         return SDValue();
5012       LDBase = cast<LoadSDNode>(Elt.getNode());
5013       LastLoadedElt = i;
5014       continue;
5015     }
5016     if (Elt.getOpcode() == ISD::UNDEF)
5017       continue;
5018
5019     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5020     EVT LdVT = Elt.getValueType();
5021     // Each loaded element must be the correct fractional portion of the
5022     // requested vector load.
5023     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5024       return SDValue();
5025     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5026       return SDValue();
5027     LastLoadedElt = i;
5028   }
5029
5030   // If we have found an entire vector of loads and undefs, then return a large
5031   // load of the entire vector width starting at the base pointer.  If we found
5032   // consecutive loads for the low half, generate a vzext_load node.
5033   if (LastLoadedElt == NumElems - 1) {
5034     assert(LDBase && "Did not find base load for merging consecutive loads");
5035     EVT EltVT = LDBase->getValueType(0);
5036     // Ensure that the input vector size for the merged loads matches the
5037     // cumulative size of the input elements.
5038     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5039       return SDValue();
5040
5041     if (isAfterLegalize &&
5042         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5043       return SDValue();
5044
5045     SDValue NewLd = SDValue();
5046
5047     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5048                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5049                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5050                         LDBase->getAlignment());
5051
5052     if (LDBase->hasAnyUseOfValue(1)) {
5053       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5054                                      SDValue(LDBase, 1),
5055                                      SDValue(NewLd.getNode(), 1));
5056       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5057       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5058                              SDValue(NewLd.getNode(), 1));
5059     }
5060
5061     return NewLd;
5062   }
5063
5064   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5065   //of a v4i32 / v4f32. It's probably worth generalizing.
5066   EVT EltVT = VT.getVectorElementType();
5067   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5068       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5069     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5070     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5071     SDValue ResNode =
5072         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5073                                 LDBase->getPointerInfo(),
5074                                 LDBase->getAlignment(),
5075                                 false/*isVolatile*/, true/*ReadMem*/,
5076                                 false/*WriteMem*/);
5077
5078     // Make sure the newly-created LOAD is in the same position as LDBase in
5079     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5080     // update uses of LDBase's output chain to use the TokenFactor.
5081     if (LDBase->hasAnyUseOfValue(1)) {
5082       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5083                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5084       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5085       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5086                              SDValue(ResNode.getNode(), 1));
5087     }
5088
5089     return DAG.getBitcast(VT, ResNode);
5090   }
5091   return SDValue();
5092 }
5093
5094 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5095 /// to generate a splat value for the following cases:
5096 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5097 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5098 /// a scalar load, or a constant.
5099 /// The VBROADCAST node is returned when a pattern is found,
5100 /// or SDValue() otherwise.
5101 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5102                                     SelectionDAG &DAG) {
5103   // VBROADCAST requires AVX.
5104   // TODO: Splats could be generated for non-AVX CPUs using SSE
5105   // instructions, but there's less potential gain for only 128-bit vectors.
5106   if (!Subtarget->hasAVX())
5107     return SDValue();
5108
5109   MVT VT = Op.getSimpleValueType();
5110   SDLoc dl(Op);
5111
5112   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5113          "Unsupported vector type for broadcast.");
5114
5115   SDValue Ld;
5116   bool ConstSplatVal;
5117
5118   switch (Op.getOpcode()) {
5119     default:
5120       // Unknown pattern found.
5121       return SDValue();
5122
5123     case ISD::BUILD_VECTOR: {
5124       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5125       BitVector UndefElements;
5126       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5127
5128       // We need a splat of a single value to use broadcast, and it doesn't
5129       // make any sense if the value is only in one element of the vector.
5130       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5131         return SDValue();
5132
5133       Ld = Splat;
5134       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5135                        Ld.getOpcode() == ISD::ConstantFP);
5136
5137       // Make sure that all of the users of a non-constant load are from the
5138       // BUILD_VECTOR node.
5139       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5140         return SDValue();
5141       break;
5142     }
5143
5144     case ISD::VECTOR_SHUFFLE: {
5145       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5146
5147       // Shuffles must have a splat mask where the first element is
5148       // broadcasted.
5149       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5150         return SDValue();
5151
5152       SDValue Sc = Op.getOperand(0);
5153       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5154           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5155
5156         if (!Subtarget->hasInt256())
5157           return SDValue();
5158
5159         // Use the register form of the broadcast instruction available on AVX2.
5160         if (VT.getSizeInBits() >= 256)
5161           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5162         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5163       }
5164
5165       Ld = Sc.getOperand(0);
5166       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5167                        Ld.getOpcode() == ISD::ConstantFP);
5168
5169       // The scalar_to_vector node and the suspected
5170       // load node must have exactly one user.
5171       // Constants may have multiple users.
5172
5173       // AVX-512 has register version of the broadcast
5174       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5175         Ld.getValueType().getSizeInBits() >= 32;
5176       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5177           !hasRegVer))
5178         return SDValue();
5179       break;
5180     }
5181   }
5182
5183   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5184   bool IsGE256 = (VT.getSizeInBits() >= 256);
5185
5186   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5187   // instruction to save 8 or more bytes of constant pool data.
5188   // TODO: If multiple splats are generated to load the same constant,
5189   // it may be detrimental to overall size. There needs to be a way to detect
5190   // that condition to know if this is truly a size win.
5191   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5192
5193   // Handle broadcasting a single constant scalar from the constant pool
5194   // into a vector.
5195   // On Sandybridge (no AVX2), it is still better to load a constant vector
5196   // from the constant pool and not to broadcast it from a scalar.
5197   // But override that restriction when optimizing for size.
5198   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5199   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5200     EVT CVT = Ld.getValueType();
5201     assert(!CVT.isVector() && "Must not broadcast a vector type");
5202
5203     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5204     // For size optimization, also splat v2f64 and v2i64, and for size opt
5205     // with AVX2, also splat i8 and i16.
5206     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5207     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5208         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5209       const Constant *C = nullptr;
5210       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5211         C = CI->getConstantIntValue();
5212       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5213         C = CF->getConstantFPValue();
5214
5215       assert(C && "Invalid constant type");
5216
5217       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5218       SDValue CP =
5219           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5220       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5221       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5222                        MachinePointerInfo::getConstantPool(),
5223                        false, false, false, Alignment);
5224
5225       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5226     }
5227   }
5228
5229   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5230
5231   // Handle AVX2 in-register broadcasts.
5232   if (!IsLoad && Subtarget->hasInt256() &&
5233       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5234     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5235
5236   // The scalar source must be a normal load.
5237   if (!IsLoad)
5238     return SDValue();
5239
5240   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5241       (Subtarget->hasVLX() && ScalarSize == 64))
5242     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5243
5244   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5245   // double since there is no vbroadcastsd xmm
5246   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5247     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5248       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5249   }
5250
5251   // Unsupported broadcast.
5252   return SDValue();
5253 }
5254
5255 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5256 /// underlying vector and index.
5257 ///
5258 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5259 /// index.
5260 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5261                                          SDValue ExtIdx) {
5262   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5263   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5264     return Idx;
5265
5266   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5267   // lowered this:
5268   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5269   // to:
5270   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5271   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5272   //                           undef)
5273   //                       Constant<0>)
5274   // In this case the vector is the extract_subvector expression and the index
5275   // is 2, as specified by the shuffle.
5276   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5277   SDValue ShuffleVec = SVOp->getOperand(0);
5278   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5279   assert(ShuffleVecVT.getVectorElementType() ==
5280          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5281
5282   int ShuffleIdx = SVOp->getMaskElt(Idx);
5283   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5284     ExtractedFromVec = ShuffleVec;
5285     return ShuffleIdx;
5286   }
5287   return Idx;
5288 }
5289
5290 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5291   MVT VT = Op.getSimpleValueType();
5292
5293   // Skip if insert_vec_elt is not supported.
5294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5295   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5296     return SDValue();
5297
5298   SDLoc DL(Op);
5299   unsigned NumElems = Op.getNumOperands();
5300
5301   SDValue VecIn1;
5302   SDValue VecIn2;
5303   SmallVector<unsigned, 4> InsertIndices;
5304   SmallVector<int, 8> Mask(NumElems, -1);
5305
5306   for (unsigned i = 0; i != NumElems; ++i) {
5307     unsigned Opc = Op.getOperand(i).getOpcode();
5308
5309     if (Opc == ISD::UNDEF)
5310       continue;
5311
5312     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5313       // Quit if more than 1 elements need inserting.
5314       if (InsertIndices.size() > 1)
5315         return SDValue();
5316
5317       InsertIndices.push_back(i);
5318       continue;
5319     }
5320
5321     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5322     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5323     // Quit if non-constant index.
5324     if (!isa<ConstantSDNode>(ExtIdx))
5325       return SDValue();
5326     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5327
5328     // Quit if extracted from vector of different type.
5329     if (ExtractedFromVec.getValueType() != VT)
5330       return SDValue();
5331
5332     if (!VecIn1.getNode())
5333       VecIn1 = ExtractedFromVec;
5334     else if (VecIn1 != ExtractedFromVec) {
5335       if (!VecIn2.getNode())
5336         VecIn2 = ExtractedFromVec;
5337       else if (VecIn2 != ExtractedFromVec)
5338         // Quit if more than 2 vectors to shuffle
5339         return SDValue();
5340     }
5341
5342     if (ExtractedFromVec == VecIn1)
5343       Mask[i] = Idx;
5344     else if (ExtractedFromVec == VecIn2)
5345       Mask[i] = Idx + NumElems;
5346   }
5347
5348   if (!VecIn1.getNode())
5349     return SDValue();
5350
5351   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5352   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5353   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5354     unsigned Idx = InsertIndices[i];
5355     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5356                      DAG.getIntPtrConstant(Idx, DL));
5357   }
5358
5359   return NV;
5360 }
5361
5362 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5363   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5364          Op.getScalarValueSizeInBits() == 1 &&
5365          "Can not convert non-constant vector");
5366   uint64_t Immediate = 0;
5367   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5368     SDValue In = Op.getOperand(idx);
5369     if (In.getOpcode() != ISD::UNDEF)
5370       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5371   }
5372   SDLoc dl(Op);
5373   MVT VT =
5374    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5375   return DAG.getConstant(Immediate, dl, VT);
5376 }
5377 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5378 SDValue
5379 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5380
5381   MVT VT = Op.getSimpleValueType();
5382   assert((VT.getVectorElementType() == MVT::i1) &&
5383          "Unexpected type in LowerBUILD_VECTORvXi1!");
5384
5385   SDLoc dl(Op);
5386   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5387     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5388     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5389     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5390   }
5391
5392   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5393     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5394     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5395     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5396   }
5397
5398   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5399     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5400     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5401       return DAG.getBitcast(VT, Imm);
5402     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5403     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5404                         DAG.getIntPtrConstant(0, dl));
5405   }
5406
5407   // Vector has one or more non-const elements
5408   uint64_t Immediate = 0;
5409   SmallVector<unsigned, 16> NonConstIdx;
5410   bool IsSplat = true;
5411   bool HasConstElts = false;
5412   int SplatIdx = -1;
5413   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5414     SDValue In = Op.getOperand(idx);
5415     if (In.getOpcode() == ISD::UNDEF)
5416       continue;
5417     if (!isa<ConstantSDNode>(In))
5418       NonConstIdx.push_back(idx);
5419     else {
5420       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5421       HasConstElts = true;
5422     }
5423     if (SplatIdx == -1)
5424       SplatIdx = idx;
5425     else if (In != Op.getOperand(SplatIdx))
5426       IsSplat = false;
5427   }
5428
5429   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5430   if (IsSplat)
5431     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5432                        DAG.getConstant(1, dl, VT),
5433                        DAG.getConstant(0, dl, VT));
5434
5435   // insert elements one by one
5436   SDValue DstVec;
5437   SDValue Imm;
5438   if (Immediate) {
5439     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5440     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5441   }
5442   else if (HasConstElts)
5443     Imm = DAG.getConstant(0, dl, VT);
5444   else
5445     Imm = DAG.getUNDEF(VT);
5446   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5447     DstVec = DAG.getBitcast(VT, Imm);
5448   else {
5449     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5450     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5451                          DAG.getIntPtrConstant(0, dl));
5452   }
5453
5454   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5455     unsigned InsertIdx = NonConstIdx[i];
5456     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5457                          Op.getOperand(InsertIdx),
5458                          DAG.getIntPtrConstant(InsertIdx, dl));
5459   }
5460   return DstVec;
5461 }
5462
5463 /// \brief Return true if \p N implements a horizontal binop and return the
5464 /// operands for the horizontal binop into V0 and V1.
5465 ///
5466 /// This is a helper function of LowerToHorizontalOp().
5467 /// This function checks that the build_vector \p N in input implements a
5468 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5469 /// operation to match.
5470 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5471 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5472 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5473 /// arithmetic sub.
5474 ///
5475 /// This function only analyzes elements of \p N whose indices are
5476 /// in range [BaseIdx, LastIdx).
5477 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5478                               SelectionDAG &DAG,
5479                               unsigned BaseIdx, unsigned LastIdx,
5480                               SDValue &V0, SDValue &V1) {
5481   EVT VT = N->getValueType(0);
5482
5483   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5484   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5485          "Invalid Vector in input!");
5486
5487   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5488   bool CanFold = true;
5489   unsigned ExpectedVExtractIdx = BaseIdx;
5490   unsigned NumElts = LastIdx - BaseIdx;
5491   V0 = DAG.getUNDEF(VT);
5492   V1 = DAG.getUNDEF(VT);
5493
5494   // Check if N implements a horizontal binop.
5495   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5496     SDValue Op = N->getOperand(i + BaseIdx);
5497
5498     // Skip UNDEFs.
5499     if (Op->getOpcode() == ISD::UNDEF) {
5500       // Update the expected vector extract index.
5501       if (i * 2 == NumElts)
5502         ExpectedVExtractIdx = BaseIdx;
5503       ExpectedVExtractIdx += 2;
5504       continue;
5505     }
5506
5507     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5508
5509     if (!CanFold)
5510       break;
5511
5512     SDValue Op0 = Op.getOperand(0);
5513     SDValue Op1 = Op.getOperand(1);
5514
5515     // Try to match the following pattern:
5516     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5517     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5518         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5519         Op0.getOperand(0) == Op1.getOperand(0) &&
5520         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5521         isa<ConstantSDNode>(Op1.getOperand(1)));
5522     if (!CanFold)
5523       break;
5524
5525     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5526     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5527
5528     if (i * 2 < NumElts) {
5529       if (V0.getOpcode() == ISD::UNDEF) {
5530         V0 = Op0.getOperand(0);
5531         if (V0.getValueType() != VT)
5532           return false;
5533       }
5534     } else {
5535       if (V1.getOpcode() == ISD::UNDEF) {
5536         V1 = Op0.getOperand(0);
5537         if (V1.getValueType() != VT)
5538           return false;
5539       }
5540       if (i * 2 == NumElts)
5541         ExpectedVExtractIdx = BaseIdx;
5542     }
5543
5544     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5545     if (I0 == ExpectedVExtractIdx)
5546       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5547     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5548       // Try to match the following dag sequence:
5549       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5550       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5551     } else
5552       CanFold = false;
5553
5554     ExpectedVExtractIdx += 2;
5555   }
5556
5557   return CanFold;
5558 }
5559
5560 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5561 /// a concat_vector.
5562 ///
5563 /// This is a helper function of LowerToHorizontalOp().
5564 /// This function expects two 256-bit vectors called V0 and V1.
5565 /// At first, each vector is split into two separate 128-bit vectors.
5566 /// Then, the resulting 128-bit vectors are used to implement two
5567 /// horizontal binary operations.
5568 ///
5569 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5570 ///
5571 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5572 /// the two new horizontal binop.
5573 /// When Mode is set, the first horizontal binop dag node would take as input
5574 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5575 /// horizontal binop dag node would take as input the lower 128-bit of V1
5576 /// and the upper 128-bit of V1.
5577 ///   Example:
5578 ///     HADD V0_LO, V0_HI
5579 ///     HADD V1_LO, V1_HI
5580 ///
5581 /// Otherwise, the first horizontal binop dag node takes as input the lower
5582 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5583 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5584 ///   Example:
5585 ///     HADD V0_LO, V1_LO
5586 ///     HADD V0_HI, V1_HI
5587 ///
5588 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5589 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5590 /// the upper 128-bits of the result.
5591 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5592                                      SDLoc DL, SelectionDAG &DAG,
5593                                      unsigned X86Opcode, bool Mode,
5594                                      bool isUndefLO, bool isUndefHI) {
5595   EVT VT = V0.getValueType();
5596   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5597          "Invalid nodes in input!");
5598
5599   unsigned NumElts = VT.getVectorNumElements();
5600   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5601   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5602   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5603   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5604   EVT NewVT = V0_LO.getValueType();
5605
5606   SDValue LO = DAG.getUNDEF(NewVT);
5607   SDValue HI = DAG.getUNDEF(NewVT);
5608
5609   if (Mode) {
5610     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5611     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5612       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5613     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5614       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5615   } else {
5616     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5617     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5618                        V1_LO->getOpcode() != ISD::UNDEF))
5619       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5620
5621     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5622                        V1_HI->getOpcode() != ISD::UNDEF))
5623       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5624   }
5625
5626   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5627 }
5628
5629 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5630 /// node.
5631 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5632                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5633   EVT VT = BV->getValueType(0);
5634   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5635       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5636     return SDValue();
5637
5638   SDLoc DL(BV);
5639   unsigned NumElts = VT.getVectorNumElements();
5640   SDValue InVec0 = DAG.getUNDEF(VT);
5641   SDValue InVec1 = DAG.getUNDEF(VT);
5642
5643   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5644           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5645
5646   // Odd-numbered elements in the input build vector are obtained from
5647   // adding two integer/float elements.
5648   // Even-numbered elements in the input build vector are obtained from
5649   // subtracting two integer/float elements.
5650   unsigned ExpectedOpcode = ISD::FSUB;
5651   unsigned NextExpectedOpcode = ISD::FADD;
5652   bool AddFound = false;
5653   bool SubFound = false;
5654
5655   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5656     SDValue Op = BV->getOperand(i);
5657
5658     // Skip 'undef' values.
5659     unsigned Opcode = Op.getOpcode();
5660     if (Opcode == ISD::UNDEF) {
5661       std::swap(ExpectedOpcode, NextExpectedOpcode);
5662       continue;
5663     }
5664
5665     // Early exit if we found an unexpected opcode.
5666     if (Opcode != ExpectedOpcode)
5667       return SDValue();
5668
5669     SDValue Op0 = Op.getOperand(0);
5670     SDValue Op1 = Op.getOperand(1);
5671
5672     // Try to match the following pattern:
5673     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5674     // Early exit if we cannot match that sequence.
5675     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5676         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5677         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5678         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5679         Op0.getOperand(1) != Op1.getOperand(1))
5680       return SDValue();
5681
5682     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5683     if (I0 != i)
5684       return SDValue();
5685
5686     // We found a valid add/sub node. Update the information accordingly.
5687     if (i & 1)
5688       AddFound = true;
5689     else
5690       SubFound = true;
5691
5692     // Update InVec0 and InVec1.
5693     if (InVec0.getOpcode() == ISD::UNDEF) {
5694       InVec0 = Op0.getOperand(0);
5695       if (InVec0.getValueType() != VT)
5696         return SDValue();
5697     }
5698     if (InVec1.getOpcode() == ISD::UNDEF) {
5699       InVec1 = Op1.getOperand(0);
5700       if (InVec1.getValueType() != VT)
5701         return SDValue();
5702     }
5703
5704     // Make sure that operands in input to each add/sub node always
5705     // come from a same pair of vectors.
5706     if (InVec0 != Op0.getOperand(0)) {
5707       if (ExpectedOpcode == ISD::FSUB)
5708         return SDValue();
5709
5710       // FADD is commutable. Try to commute the operands
5711       // and then test again.
5712       std::swap(Op0, Op1);
5713       if (InVec0 != Op0.getOperand(0))
5714         return SDValue();
5715     }
5716
5717     if (InVec1 != Op1.getOperand(0))
5718       return SDValue();
5719
5720     // Update the pair of expected opcodes.
5721     std::swap(ExpectedOpcode, NextExpectedOpcode);
5722   }
5723
5724   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5725   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5726       InVec1.getOpcode() != ISD::UNDEF)
5727     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5728
5729   return SDValue();
5730 }
5731
5732 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5733 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5734                                    const X86Subtarget *Subtarget,
5735                                    SelectionDAG &DAG) {
5736   EVT VT = BV->getValueType(0);
5737   unsigned NumElts = VT.getVectorNumElements();
5738   unsigned NumUndefsLO = 0;
5739   unsigned NumUndefsHI = 0;
5740   unsigned Half = NumElts/2;
5741
5742   // Count the number of UNDEF operands in the build_vector in input.
5743   for (unsigned i = 0, e = Half; i != e; ++i)
5744     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5745       NumUndefsLO++;
5746
5747   for (unsigned i = Half, e = NumElts; i != e; ++i)
5748     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5749       NumUndefsHI++;
5750
5751   // Early exit if this is either a build_vector of all UNDEFs or all the
5752   // operands but one are UNDEF.
5753   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5754     return SDValue();
5755
5756   SDLoc DL(BV);
5757   SDValue InVec0, InVec1;
5758   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5759     // Try to match an SSE3 float HADD/HSUB.
5760     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5761       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5762
5763     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5764       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5765   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5766     // Try to match an SSSE3 integer HADD/HSUB.
5767     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5768       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5769
5770     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5771       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5772   }
5773
5774   if (!Subtarget->hasAVX())
5775     return SDValue();
5776
5777   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5778     // Try to match an AVX horizontal add/sub of packed single/double
5779     // precision floating point values from 256-bit vectors.
5780     SDValue InVec2, InVec3;
5781     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5782         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5783         ((InVec0.getOpcode() == ISD::UNDEF ||
5784           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5785         ((InVec1.getOpcode() == ISD::UNDEF ||
5786           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5787       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5788
5789     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5790         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5791         ((InVec0.getOpcode() == ISD::UNDEF ||
5792           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5793         ((InVec1.getOpcode() == ISD::UNDEF ||
5794           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5795       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5796   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5797     // Try to match an AVX2 horizontal add/sub of signed integers.
5798     SDValue InVec2, InVec3;
5799     unsigned X86Opcode;
5800     bool CanFold = true;
5801
5802     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5803         isHorizontalBinOp(BV, ISD::ADD, 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       X86Opcode = X86ISD::HADD;
5809     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5810         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5811         ((InVec0.getOpcode() == ISD::UNDEF ||
5812           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5813         ((InVec1.getOpcode() == ISD::UNDEF ||
5814           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5815       X86Opcode = X86ISD::HSUB;
5816     else
5817       CanFold = false;
5818
5819     if (CanFold) {
5820       // Fold this build_vector into a single horizontal add/sub.
5821       // Do this only if the target has AVX2.
5822       if (Subtarget->hasAVX2())
5823         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5824
5825       // Do not try to expand this build_vector into a pair of horizontal
5826       // add/sub if we can emit a pair of scalar add/sub.
5827       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5828         return SDValue();
5829
5830       // Convert this build_vector into a pair of horizontal binop followed by
5831       // a concat vector.
5832       bool isUndefLO = NumUndefsLO == Half;
5833       bool isUndefHI = NumUndefsHI == Half;
5834       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5835                                    isUndefLO, isUndefHI);
5836     }
5837   }
5838
5839   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5840        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5841     unsigned X86Opcode;
5842     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5843       X86Opcode = X86ISD::HADD;
5844     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5845       X86Opcode = X86ISD::HSUB;
5846     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5847       X86Opcode = X86ISD::FHADD;
5848     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5849       X86Opcode = X86ISD::FHSUB;
5850     else
5851       return SDValue();
5852
5853     // Don't try to expand this build_vector into a pair of horizontal add/sub
5854     // if we can simply emit a pair of scalar add/sub.
5855     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5856       return SDValue();
5857
5858     // Convert this build_vector into two horizontal add/sub followed by
5859     // a concat vector.
5860     bool isUndefLO = NumUndefsLO == Half;
5861     bool isUndefHI = NumUndefsHI == Half;
5862     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5863                                  isUndefLO, isUndefHI);
5864   }
5865
5866   return SDValue();
5867 }
5868
5869 SDValue
5870 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5871   SDLoc dl(Op);
5872
5873   MVT VT = Op.getSimpleValueType();
5874   MVT ExtVT = VT.getVectorElementType();
5875   unsigned NumElems = Op.getNumOperands();
5876
5877   // Generate vectors for predicate vectors.
5878   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5879     return LowerBUILD_VECTORvXi1(Op, DAG);
5880
5881   // Vectors containing all zeros can be matched by pxor and xorps later
5882   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5883     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5884     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5885     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5886       return Op;
5887
5888     return getZeroVector(VT, Subtarget, DAG, dl);
5889   }
5890
5891   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5892   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5893   // vpcmpeqd on 256-bit vectors.
5894   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5895     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5896       return Op;
5897
5898     if (!VT.is512BitVector())
5899       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5900   }
5901
5902   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5903   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5904     return AddSub;
5905   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5906     return HorizontalOp;
5907   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5908     return Broadcast;
5909
5910   unsigned EVTBits = ExtVT.getSizeInBits();
5911
5912   unsigned NumZero  = 0;
5913   unsigned NumNonZero = 0;
5914   unsigned NonZeros = 0;
5915   bool IsAllConstants = true;
5916   SmallSet<SDValue, 8> Values;
5917   for (unsigned i = 0; i < NumElems; ++i) {
5918     SDValue Elt = Op.getOperand(i);
5919     if (Elt.getOpcode() == ISD::UNDEF)
5920       continue;
5921     Values.insert(Elt);
5922     if (Elt.getOpcode() != ISD::Constant &&
5923         Elt.getOpcode() != ISD::ConstantFP)
5924       IsAllConstants = false;
5925     if (X86::isZeroNode(Elt))
5926       NumZero++;
5927     else {
5928       NonZeros |= (1 << i);
5929       NumNonZero++;
5930     }
5931   }
5932
5933   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5934   if (NumNonZero == 0)
5935     return DAG.getUNDEF(VT);
5936
5937   // Special case for single non-zero, non-undef, element.
5938   if (NumNonZero == 1) {
5939     unsigned Idx = countTrailingZeros(NonZeros);
5940     SDValue Item = Op.getOperand(Idx);
5941
5942     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5943     // the value are obviously zero, truncate the value to i32 and do the
5944     // insertion that way.  Only do this if the value is non-constant or if the
5945     // value is a constant being inserted into element 0.  It is cheaper to do
5946     // a constant pool load than it is to do a movd + shuffle.
5947     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5948         (!IsAllConstants || Idx == 0)) {
5949       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5950         // Handle SSE only.
5951         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5952         EVT VecVT = MVT::v4i32;
5953
5954         // Truncate the value (which may itself be a constant) to i32, and
5955         // convert it to a vector with movd (S2V+shuffle to zero extend).
5956         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5957         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5958         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5959                                       Item, Idx * 2, true, Subtarget, DAG));
5960       }
5961     }
5962
5963     // If we have a constant or non-constant insertion into the low element of
5964     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5965     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5966     // depending on what the source datatype is.
5967     if (Idx == 0) {
5968       if (NumZero == 0)
5969         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5970
5971       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5972           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5973         if (VT.is512BitVector()) {
5974           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5975           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5976                              Item, DAG.getIntPtrConstant(0, dl));
5977         }
5978         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5979                "Expected an SSE value type!");
5980         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5981         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5982         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5983       }
5984
5985       // We can't directly insert an i8 or i16 into a vector, so zero extend
5986       // it to i32 first.
5987       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5988         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5989         if (VT.is256BitVector()) {
5990           if (Subtarget->hasAVX()) {
5991             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5992             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5993           } else {
5994             // Without AVX, we need to extend to a 128-bit vector and then
5995             // insert into the 256-bit vector.
5996             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5997             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5998             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5999           }
6000         } else {
6001           assert(VT.is128BitVector() && "Expected an SSE value type!");
6002           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6003           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6004         }
6005         return DAG.getBitcast(VT, Item);
6006       }
6007     }
6008
6009     // Is it a vector logical left shift?
6010     if (NumElems == 2 && Idx == 1 &&
6011         X86::isZeroNode(Op.getOperand(0)) &&
6012         !X86::isZeroNode(Op.getOperand(1))) {
6013       unsigned NumBits = VT.getSizeInBits();
6014       return getVShift(true, VT,
6015                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6016                                    VT, Op.getOperand(1)),
6017                        NumBits/2, DAG, *this, dl);
6018     }
6019
6020     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6021       return SDValue();
6022
6023     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6024     // is a non-constant being inserted into an element other than the low one,
6025     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6026     // movd/movss) to move this into the low element, then shuffle it into
6027     // place.
6028     if (EVTBits == 32) {
6029       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6030       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6031     }
6032   }
6033
6034   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6035   if (Values.size() == 1) {
6036     if (EVTBits == 32) {
6037       // Instead of a shuffle like this:
6038       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6039       // Check if it's possible to issue this instead.
6040       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6041       unsigned Idx = countTrailingZeros(NonZeros);
6042       SDValue Item = Op.getOperand(Idx);
6043       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6044         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6045     }
6046     return SDValue();
6047   }
6048
6049   // A vector full of immediates; various special cases are already
6050   // handled, so this is best done with a single constant-pool load.
6051   if (IsAllConstants)
6052     return SDValue();
6053
6054   // For AVX-length vectors, see if we can use a vector load to get all of the
6055   // elements, otherwise build the individual 128-bit pieces and use
6056   // shuffles to put them in place.
6057   if (VT.is256BitVector() || VT.is512BitVector()) {
6058     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6059
6060     // Check for a build vector of consecutive loads.
6061     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6062       return LD;
6063
6064     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6065
6066     // Build both the lower and upper subvector.
6067     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6068                                 makeArrayRef(&V[0], NumElems/2));
6069     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6070                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6071
6072     // Recreate the wider vector with the lower and upper part.
6073     if (VT.is256BitVector())
6074       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6075     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6076   }
6077
6078   // Let legalizer expand 2-wide build_vectors.
6079   if (EVTBits == 64) {
6080     if (NumNonZero == 1) {
6081       // One half is zero or undef.
6082       unsigned Idx = countTrailingZeros(NonZeros);
6083       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6084                                  Op.getOperand(Idx));
6085       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6086     }
6087     return SDValue();
6088   }
6089
6090   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6091   if (EVTBits == 8 && NumElems == 16)
6092     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6093                                         Subtarget, *this))
6094       return V;
6095
6096   if (EVTBits == 16 && NumElems == 8)
6097     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6098                                       Subtarget, *this))
6099       return V;
6100
6101   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6102   if (EVTBits == 32 && NumElems == 4)
6103     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6104       return V;
6105
6106   // If element VT is == 32 bits, turn it into a number of shuffles.
6107   SmallVector<SDValue, 8> V(NumElems);
6108   if (NumElems == 4 && NumZero > 0) {
6109     for (unsigned i = 0; i < 4; ++i) {
6110       bool isZero = !(NonZeros & (1 << i));
6111       if (isZero)
6112         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6113       else
6114         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6115     }
6116
6117     for (unsigned i = 0; i < 2; ++i) {
6118       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6119         default: break;
6120         case 0:
6121           V[i] = V[i*2];  // Must be a zero vector.
6122           break;
6123         case 1:
6124           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6125           break;
6126         case 2:
6127           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6128           break;
6129         case 3:
6130           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6131           break;
6132       }
6133     }
6134
6135     bool Reverse1 = (NonZeros & 0x3) == 2;
6136     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6137     int MaskVec[] = {
6138       Reverse1 ? 1 : 0,
6139       Reverse1 ? 0 : 1,
6140       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6141       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6142     };
6143     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6144   }
6145
6146   if (Values.size() > 1 && VT.is128BitVector()) {
6147     // Check for a build vector of consecutive loads.
6148     for (unsigned i = 0; i < NumElems; ++i)
6149       V[i] = Op.getOperand(i);
6150
6151     // Check for elements which are consecutive loads.
6152     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6153       return LD;
6154
6155     // Check for a build vector from mostly shuffle plus few inserting.
6156     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6157       return Sh;
6158
6159     // For SSE 4.1, use insertps to put the high elements into the low element.
6160     if (Subtarget->hasSSE41()) {
6161       SDValue Result;
6162       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6163         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6164       else
6165         Result = DAG.getUNDEF(VT);
6166
6167       for (unsigned i = 1; i < NumElems; ++i) {
6168         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6169         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6170                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6171       }
6172       return Result;
6173     }
6174
6175     // Otherwise, expand into a number of unpckl*, start by extending each of
6176     // our (non-undef) elements to the full vector width with the element in the
6177     // bottom slot of the vector (which generates no code for SSE).
6178     for (unsigned i = 0; i < NumElems; ++i) {
6179       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6180         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6181       else
6182         V[i] = DAG.getUNDEF(VT);
6183     }
6184
6185     // Next, we iteratively mix elements, e.g. for v4f32:
6186     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6187     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6188     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6189     unsigned EltStride = NumElems >> 1;
6190     while (EltStride != 0) {
6191       for (unsigned i = 0; i < EltStride; ++i) {
6192         // If V[i+EltStride] is undef and this is the first round of mixing,
6193         // then it is safe to just drop this shuffle: V[i] is already in the
6194         // right place, the one element (since it's the first round) being
6195         // inserted as undef can be dropped.  This isn't safe for successive
6196         // rounds because they will permute elements within both vectors.
6197         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6198             EltStride == NumElems/2)
6199           continue;
6200
6201         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6202       }
6203       EltStride >>= 1;
6204     }
6205     return V[0];
6206   }
6207   return SDValue();
6208 }
6209
6210 // 256-bit AVX can use the vinsertf128 instruction
6211 // to create 256-bit vectors from two other 128-bit ones.
6212 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6213   SDLoc dl(Op);
6214   MVT ResVT = Op.getSimpleValueType();
6215
6216   assert((ResVT.is256BitVector() ||
6217           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6218
6219   SDValue V1 = Op.getOperand(0);
6220   SDValue V2 = Op.getOperand(1);
6221   unsigned NumElems = ResVT.getVectorNumElements();
6222   if (ResVT.is256BitVector())
6223     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6224
6225   if (Op.getNumOperands() == 4) {
6226     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6227                                 ResVT.getVectorNumElements()/2);
6228     SDValue V3 = Op.getOperand(2);
6229     SDValue V4 = Op.getOperand(3);
6230     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6231       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6232   }
6233   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6234 }
6235
6236 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6237                                        const X86Subtarget *Subtarget,
6238                                        SelectionDAG & DAG) {
6239   SDLoc dl(Op);
6240   MVT ResVT = Op.getSimpleValueType();
6241   unsigned NumOfOperands = Op.getNumOperands();
6242
6243   assert(isPowerOf2_32(NumOfOperands) &&
6244          "Unexpected number of operands in CONCAT_VECTORS");
6245
6246   if (NumOfOperands > 2) {
6247     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6248                                   ResVT.getVectorNumElements()/2);
6249     SmallVector<SDValue, 2> Ops;
6250     for (unsigned i = 0; i < NumOfOperands/2; i++)
6251       Ops.push_back(Op.getOperand(i));
6252     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6253     Ops.clear();
6254     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6255       Ops.push_back(Op.getOperand(i));
6256     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6257     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6258   }
6259
6260   SDValue V1 = Op.getOperand(0);
6261   SDValue V2 = Op.getOperand(1);
6262   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6263   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6264
6265   if (IsZeroV1 && IsZeroV2)
6266     return getZeroVector(ResVT, Subtarget, DAG, dl);
6267
6268   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6269   SDValue Undef = DAG.getUNDEF(ResVT);
6270   unsigned NumElems = ResVT.getVectorNumElements();
6271   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6272
6273   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6274   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6275   if (IsZeroV1)
6276     return V2;
6277
6278   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6279   // Zero the upper bits of V1
6280   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6281   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6282   if (IsZeroV2)
6283     return V1;
6284   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6285 }
6286
6287 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6288                                    const X86Subtarget *Subtarget,
6289                                    SelectionDAG &DAG) {
6290   MVT VT = Op.getSimpleValueType();
6291   if (VT.getVectorElementType() == MVT::i1)
6292     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6293
6294   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6295          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6296           Op.getNumOperands() == 4)));
6297
6298   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6299   // from two other 128-bit ones.
6300
6301   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6302   return LowerAVXCONCAT_VECTORS(Op, DAG);
6303 }
6304
6305
6306 //===----------------------------------------------------------------------===//
6307 // Vector shuffle lowering
6308 //
6309 // This is an experimental code path for lowering vector shuffles on x86. It is
6310 // designed to handle arbitrary vector shuffles and blends, gracefully
6311 // degrading performance as necessary. It works hard to recognize idiomatic
6312 // shuffles and lower them to optimal instruction patterns without leaving
6313 // a framework that allows reasonably efficient handling of all vector shuffle
6314 // patterns.
6315 //===----------------------------------------------------------------------===//
6316
6317 /// \brief Tiny helper function to identify a no-op mask.
6318 ///
6319 /// This is a somewhat boring predicate function. It checks whether the mask
6320 /// array input, which is assumed to be a single-input shuffle mask of the kind
6321 /// used by the X86 shuffle instructions (not a fully general
6322 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6323 /// in-place shuffle are 'no-op's.
6324 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6325   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6326     if (Mask[i] != -1 && Mask[i] != i)
6327       return false;
6328   return true;
6329 }
6330
6331 /// \brief Helper function to classify a mask as a single-input mask.
6332 ///
6333 /// This isn't a generic single-input test because in the vector shuffle
6334 /// lowering we canonicalize single inputs to be the first input operand. This
6335 /// means we can more quickly test for a single input by only checking whether
6336 /// an input from the second operand exists. We also assume that the size of
6337 /// mask corresponds to the size of the input vectors which isn't true in the
6338 /// fully general case.
6339 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6340   for (int M : Mask)
6341     if (M >= (int)Mask.size())
6342       return false;
6343   return true;
6344 }
6345
6346 /// \brief Test whether there are elements crossing 128-bit lanes in this
6347 /// shuffle mask.
6348 ///
6349 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6350 /// and we routinely test for these.
6351 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6352   int LaneSize = 128 / VT.getScalarSizeInBits();
6353   int Size = Mask.size();
6354   for (int i = 0; i < Size; ++i)
6355     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6356       return true;
6357   return false;
6358 }
6359
6360 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6361 ///
6362 /// This checks a shuffle mask to see if it is performing the same
6363 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6364 /// that it is also not lane-crossing. It may however involve a blend from the
6365 /// same lane of a second vector.
6366 ///
6367 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6368 /// non-trivial to compute in the face of undef lanes. The representation is
6369 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6370 /// entries from both V1 and V2 inputs to the wider mask.
6371 static bool
6372 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6373                                 SmallVectorImpl<int> &RepeatedMask) {
6374   int LaneSize = 128 / VT.getScalarSizeInBits();
6375   RepeatedMask.resize(LaneSize, -1);
6376   int Size = Mask.size();
6377   for (int i = 0; i < Size; ++i) {
6378     if (Mask[i] < 0)
6379       continue;
6380     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6381       // This entry crosses lanes, so there is no way to model this shuffle.
6382       return false;
6383
6384     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6385     if (RepeatedMask[i % LaneSize] == -1)
6386       // This is the first non-undef entry in this slot of a 128-bit lane.
6387       RepeatedMask[i % LaneSize] =
6388           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6389     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6390       // Found a mismatch with the repeated mask.
6391       return false;
6392   }
6393   return true;
6394 }
6395
6396 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6397 /// arguments.
6398 ///
6399 /// This is a fast way to test a shuffle mask against a fixed pattern:
6400 ///
6401 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6402 ///
6403 /// It returns true if the mask is exactly as wide as the argument list, and
6404 /// each element of the mask is either -1 (signifying undef) or the value given
6405 /// in the argument.
6406 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6407                                 ArrayRef<int> ExpectedMask) {
6408   if (Mask.size() != ExpectedMask.size())
6409     return false;
6410
6411   int Size = Mask.size();
6412
6413   // If the values are build vectors, we can look through them to find
6414   // equivalent inputs that make the shuffles equivalent.
6415   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6416   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6417
6418   for (int i = 0; i < Size; ++i)
6419     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6420       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6421       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6422       if (!MaskBV || !ExpectedBV ||
6423           MaskBV->getOperand(Mask[i] % Size) !=
6424               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6425         return false;
6426     }
6427
6428   return true;
6429 }
6430
6431 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6432 ///
6433 /// This helper function produces an 8-bit shuffle immediate corresponding to
6434 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6435 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6436 /// example.
6437 ///
6438 /// NB: We rely heavily on "undef" masks preserving the input lane.
6439 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6440                                           SelectionDAG &DAG) {
6441   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6442   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6443   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6444   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6445   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6446
6447   unsigned Imm = 0;
6448   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6449   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6450   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6451   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6452   return DAG.getConstant(Imm, DL, MVT::i8);
6453 }
6454
6455 /// \brief Compute whether each element of a shuffle is zeroable.
6456 ///
6457 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6458 /// Either it is an undef element in the shuffle mask, the element of the input
6459 /// referenced is undef, or the element of the input referenced is known to be
6460 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6461 /// as many lanes with this technique as possible to simplify the remaining
6462 /// shuffle.
6463 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6464                                                      SDValue V1, SDValue V2) {
6465   SmallBitVector Zeroable(Mask.size(), false);
6466
6467   while (V1.getOpcode() == ISD::BITCAST)
6468     V1 = V1->getOperand(0);
6469   while (V2.getOpcode() == ISD::BITCAST)
6470     V2 = V2->getOperand(0);
6471
6472   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6473   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6474
6475   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6476     int M = Mask[i];
6477     // Handle the easy cases.
6478     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6479       Zeroable[i] = true;
6480       continue;
6481     }
6482
6483     // If this is an index into a build_vector node (which has the same number
6484     // of elements), dig out the input value and use it.
6485     SDValue V = M < Size ? V1 : V2;
6486     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6487       continue;
6488
6489     SDValue Input = V.getOperand(M % Size);
6490     // The UNDEF opcode check really should be dead code here, but not quite
6491     // worth asserting on (it isn't invalid, just unexpected).
6492     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6493       Zeroable[i] = true;
6494   }
6495
6496   return Zeroable;
6497 }
6498
6499 /// \brief Try to emit a bitmask instruction for a shuffle.
6500 ///
6501 /// This handles cases where we can model a blend exactly as a bitmask due to
6502 /// one of the inputs being zeroable.
6503 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6504                                            SDValue V2, ArrayRef<int> Mask,
6505                                            SelectionDAG &DAG) {
6506   MVT EltVT = VT.getScalarType();
6507   int NumEltBits = EltVT.getSizeInBits();
6508   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6509   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6510   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6511                                     IntEltVT);
6512   if (EltVT.isFloatingPoint()) {
6513     Zero = DAG.getBitcast(EltVT, Zero);
6514     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6515   }
6516   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6517   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6518   SDValue V;
6519   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6520     if (Zeroable[i])
6521       continue;
6522     if (Mask[i] % Size != i)
6523       return SDValue(); // Not a blend.
6524     if (!V)
6525       V = Mask[i] < Size ? V1 : V2;
6526     else if (V != (Mask[i] < Size ? V1 : V2))
6527       return SDValue(); // Can only let one input through the mask.
6528
6529     VMaskOps[i] = AllOnes;
6530   }
6531   if (!V)
6532     return SDValue(); // No non-zeroable elements!
6533
6534   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6535   V = DAG.getNode(VT.isFloatingPoint()
6536                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6537                   DL, VT, V, VMask);
6538   return V;
6539 }
6540
6541 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6542 ///
6543 /// This is used as a fallback approach when first class blend instructions are
6544 /// unavailable. Currently it is only suitable for integer vectors, but could
6545 /// be generalized for floating point vectors if desirable.
6546 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6547                                             SDValue V2, ArrayRef<int> Mask,
6548                                             SelectionDAG &DAG) {
6549   assert(VT.isInteger() && "Only supports integer vector types!");
6550   MVT EltVT = VT.getScalarType();
6551   int NumEltBits = EltVT.getSizeInBits();
6552   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6553   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6554                                     EltVT);
6555   SmallVector<SDValue, 16> MaskOps;
6556   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6557     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6558       return SDValue(); // Shuffled input!
6559     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6560   }
6561
6562   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6563   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6564   // We have to cast V2 around.
6565   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6566   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6567                                       DAG.getBitcast(MaskVT, V1Mask),
6568                                       DAG.getBitcast(MaskVT, V2)));
6569   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6570 }
6571
6572 /// \brief Try to emit a blend instruction for a shuffle.
6573 ///
6574 /// This doesn't do any checks for the availability of instructions for blending
6575 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6576 /// be matched in the backend with the type given. What it does check for is
6577 /// that the shuffle mask is in fact a blend.
6578 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6579                                          SDValue V2, ArrayRef<int> Mask,
6580                                          const X86Subtarget *Subtarget,
6581                                          SelectionDAG &DAG) {
6582   unsigned BlendMask = 0;
6583   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6584     if (Mask[i] >= Size) {
6585       if (Mask[i] != i + Size)
6586         return SDValue(); // Shuffled V2 input!
6587       BlendMask |= 1u << i;
6588       continue;
6589     }
6590     if (Mask[i] >= 0 && Mask[i] != i)
6591       return SDValue(); // Shuffled V1 input!
6592   }
6593   switch (VT.SimpleTy) {
6594   case MVT::v2f64:
6595   case MVT::v4f32:
6596   case MVT::v4f64:
6597   case MVT::v8f32:
6598     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6599                        DAG.getConstant(BlendMask, DL, MVT::i8));
6600
6601   case MVT::v4i64:
6602   case MVT::v8i32:
6603     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6604     // FALLTHROUGH
6605   case MVT::v2i64:
6606   case MVT::v4i32:
6607     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6608     // that instruction.
6609     if (Subtarget->hasAVX2()) {
6610       // Scale the blend by the number of 32-bit dwords per element.
6611       int Scale =  VT.getScalarSizeInBits() / 32;
6612       BlendMask = 0;
6613       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6614         if (Mask[i] >= Size)
6615           for (int j = 0; j < Scale; ++j)
6616             BlendMask |= 1u << (i * Scale + j);
6617
6618       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6619       V1 = DAG.getBitcast(BlendVT, V1);
6620       V2 = DAG.getBitcast(BlendVT, V2);
6621       return DAG.getBitcast(
6622           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6623                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6624     }
6625     // FALLTHROUGH
6626   case MVT::v8i16: {
6627     // For integer shuffles we need to expand the mask and cast the inputs to
6628     // v8i16s prior to blending.
6629     int Scale = 8 / VT.getVectorNumElements();
6630     BlendMask = 0;
6631     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6632       if (Mask[i] >= Size)
6633         for (int j = 0; j < Scale; ++j)
6634           BlendMask |= 1u << (i * Scale + j);
6635
6636     V1 = DAG.getBitcast(MVT::v8i16, V1);
6637     V2 = DAG.getBitcast(MVT::v8i16, V2);
6638     return DAG.getBitcast(VT,
6639                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6640                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6641   }
6642
6643   case MVT::v16i16: {
6644     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6645     SmallVector<int, 8> RepeatedMask;
6646     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6647       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6648       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6649       BlendMask = 0;
6650       for (int i = 0; i < 8; ++i)
6651         if (RepeatedMask[i] >= 16)
6652           BlendMask |= 1u << i;
6653       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6654                          DAG.getConstant(BlendMask, DL, MVT::i8));
6655     }
6656   }
6657     // FALLTHROUGH
6658   case MVT::v16i8:
6659   case MVT::v32i8: {
6660     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6661            "256-bit byte-blends require AVX2 support!");
6662
6663     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6664     if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6665       return Masked;
6666
6667     // Scale the blend by the number of bytes per element.
6668     int Scale = VT.getScalarSizeInBits() / 8;
6669
6670     // This form of blend is always done on bytes. Compute the byte vector
6671     // type.
6672     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6673
6674     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6675     // mix of LLVM's code generator and the x86 backend. We tell the code
6676     // generator that boolean values in the elements of an x86 vector register
6677     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6678     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6679     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6680     // of the element (the remaining are ignored) and 0 in that high bit would
6681     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6682     // the LLVM model for boolean values in vector elements gets the relevant
6683     // bit set, it is set backwards and over constrained relative to x86's
6684     // actual model.
6685     SmallVector<SDValue, 32> VSELECTMask;
6686     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6687       for (int j = 0; j < Scale; ++j)
6688         VSELECTMask.push_back(
6689             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6690                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6691                                           MVT::i8));
6692
6693     V1 = DAG.getBitcast(BlendVT, V1);
6694     V2 = DAG.getBitcast(BlendVT, V2);
6695     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6696                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6697                                                       BlendVT, VSELECTMask),
6698                                           V1, V2));
6699   }
6700
6701   default:
6702     llvm_unreachable("Not a supported integer vector type!");
6703   }
6704 }
6705
6706 /// \brief Try to lower as a blend of elements from two inputs followed by
6707 /// a single-input permutation.
6708 ///
6709 /// This matches the pattern where we can blend elements from two inputs and
6710 /// then reduce the shuffle to a single-input permutation.
6711 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6712                                                    SDValue V2,
6713                                                    ArrayRef<int> Mask,
6714                                                    SelectionDAG &DAG) {
6715   // We build up the blend mask while checking whether a blend is a viable way
6716   // to reduce the shuffle.
6717   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6718   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6719
6720   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6721     if (Mask[i] < 0)
6722       continue;
6723
6724     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6725
6726     if (BlendMask[Mask[i] % Size] == -1)
6727       BlendMask[Mask[i] % Size] = Mask[i];
6728     else if (BlendMask[Mask[i] % Size] != Mask[i])
6729       return SDValue(); // Can't blend in the needed input!
6730
6731     PermuteMask[i] = Mask[i] % Size;
6732   }
6733
6734   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6735   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6736 }
6737
6738 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6739 /// blends and permutes.
6740 ///
6741 /// This matches the extremely common pattern for handling combined
6742 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6743 /// operations. It will try to pick the best arrangement of shuffles and
6744 /// blends.
6745 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6746                                                           SDValue V1,
6747                                                           SDValue V2,
6748                                                           ArrayRef<int> Mask,
6749                                                           SelectionDAG &DAG) {
6750   // Shuffle the input elements into the desired positions in V1 and V2 and
6751   // blend them together.
6752   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6753   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6754   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6755   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6756     if (Mask[i] >= 0 && Mask[i] < Size) {
6757       V1Mask[i] = Mask[i];
6758       BlendMask[i] = i;
6759     } else if (Mask[i] >= Size) {
6760       V2Mask[i] = Mask[i] - Size;
6761       BlendMask[i] = i + Size;
6762     }
6763
6764   // Try to lower with the simpler initial blend strategy unless one of the
6765   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6766   // shuffle may be able to fold with a load or other benefit. However, when
6767   // we'll have to do 2x as many shuffles in order to achieve this, blending
6768   // first is a better strategy.
6769   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6770     if (SDValue BlendPerm =
6771             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6772       return BlendPerm;
6773
6774   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6775   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6776   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6777 }
6778
6779 /// \brief Try to lower a vector shuffle as a byte rotation.
6780 ///
6781 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6782 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6783 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6784 /// try to generically lower a vector shuffle through such an pattern. It
6785 /// does not check for the profitability of lowering either as PALIGNR or
6786 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6787 /// This matches shuffle vectors that look like:
6788 ///
6789 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6790 ///
6791 /// Essentially it concatenates V1 and V2, shifts right by some number of
6792 /// elements, and takes the low elements as the result. Note that while this is
6793 /// specified as a *right shift* because x86 is little-endian, it is a *left
6794 /// rotate* of the vector lanes.
6795 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6796                                               SDValue V2,
6797                                               ArrayRef<int> Mask,
6798                                               const X86Subtarget *Subtarget,
6799                                               SelectionDAG &DAG) {
6800   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6801
6802   int NumElts = Mask.size();
6803   int NumLanes = VT.getSizeInBits() / 128;
6804   int NumLaneElts = NumElts / NumLanes;
6805
6806   // We need to detect various ways of spelling a rotation:
6807   //   [11, 12, 13, 14, 15,  0,  1,  2]
6808   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6809   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6810   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6811   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6812   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6813   int Rotation = 0;
6814   SDValue Lo, Hi;
6815   for (int l = 0; l < NumElts; l += NumLaneElts) {
6816     for (int i = 0; i < NumLaneElts; ++i) {
6817       if (Mask[l + i] == -1)
6818         continue;
6819       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6820
6821       // Get the mod-Size index and lane correct it.
6822       int LaneIdx = (Mask[l + i] % NumElts) - l;
6823       // Make sure it was in this lane.
6824       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6825         return SDValue();
6826
6827       // Determine where a rotated vector would have started.
6828       int StartIdx = i - LaneIdx;
6829       if (StartIdx == 0)
6830         // The identity rotation isn't interesting, stop.
6831         return SDValue();
6832
6833       // If we found the tail of a vector the rotation must be the missing
6834       // front. If we found the head of a vector, it must be how much of the
6835       // head.
6836       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6837
6838       if (Rotation == 0)
6839         Rotation = CandidateRotation;
6840       else if (Rotation != CandidateRotation)
6841         // The rotations don't match, so we can't match this mask.
6842         return SDValue();
6843
6844       // Compute which value this mask is pointing at.
6845       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6846
6847       // Compute which of the two target values this index should be assigned
6848       // to. This reflects whether the high elements are remaining or the low
6849       // elements are remaining.
6850       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6851
6852       // Either set up this value if we've not encountered it before, or check
6853       // that it remains consistent.
6854       if (!TargetV)
6855         TargetV = MaskV;
6856       else if (TargetV != MaskV)
6857         // This may be a rotation, but it pulls from the inputs in some
6858         // unsupported interleaving.
6859         return SDValue();
6860     }
6861   }
6862
6863   // Check that we successfully analyzed the mask, and normalize the results.
6864   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6865   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6866   if (!Lo)
6867     Lo = Hi;
6868   else if (!Hi)
6869     Hi = Lo;
6870
6871   // The actual rotate instruction rotates bytes, so we need to scale the
6872   // rotation based on how many bytes are in the vector lane.
6873   int Scale = 16 / NumLaneElts;
6874
6875   // SSSE3 targets can use the palignr instruction.
6876   if (Subtarget->hasSSSE3()) {
6877     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6878     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6879     Lo = DAG.getBitcast(AlignVT, Lo);
6880     Hi = DAG.getBitcast(AlignVT, Hi);
6881
6882     return DAG.getBitcast(
6883         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6884                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6885   }
6886
6887   assert(VT.getSizeInBits() == 128 &&
6888          "Rotate-based lowering only supports 128-bit lowering!");
6889   assert(Mask.size() <= 16 &&
6890          "Can shuffle at most 16 bytes in a 128-bit vector!");
6891
6892   // Default SSE2 implementation
6893   int LoByteShift = 16 - Rotation * Scale;
6894   int HiByteShift = Rotation * Scale;
6895
6896   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6897   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6898   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6899
6900   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6901                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6902   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6903                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6904   return DAG.getBitcast(VT,
6905                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6906 }
6907
6908 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6909 ///
6910 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6911 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6912 /// matches elements from one of the input vectors shuffled to the left or
6913 /// right with zeroable elements 'shifted in'. It handles both the strictly
6914 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6915 /// quad word lane.
6916 ///
6917 /// PSHL : (little-endian) left bit shift.
6918 /// [ zz, 0, zz,  2 ]
6919 /// [ -1, 4, zz, -1 ]
6920 /// PSRL : (little-endian) right bit shift.
6921 /// [  1, zz,  3, zz]
6922 /// [ -1, -1,  7, zz]
6923 /// PSLLDQ : (little-endian) left byte shift
6924 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6925 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6926 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6927 /// PSRLDQ : (little-endian) right byte shift
6928 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6929 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6930 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6931 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6932                                          SDValue V2, ArrayRef<int> Mask,
6933                                          SelectionDAG &DAG) {
6934   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6935
6936   int Size = Mask.size();
6937   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6938
6939   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6940     for (int i = 0; i < Size; i += Scale)
6941       for (int j = 0; j < Shift; ++j)
6942         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6943           return false;
6944
6945     return true;
6946   };
6947
6948   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6949     for (int i = 0; i != Size; i += Scale) {
6950       unsigned Pos = Left ? i + Shift : i;
6951       unsigned Low = Left ? i : i + Shift;
6952       unsigned Len = Scale - Shift;
6953       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6954                                       Low + (V == V1 ? 0 : Size)))
6955         return SDValue();
6956     }
6957
6958     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6959     bool ByteShift = ShiftEltBits > 64;
6960     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6961                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6962     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6963
6964     // Normalize the scale for byte shifts to still produce an i64 element
6965     // type.
6966     Scale = ByteShift ? Scale / 2 : Scale;
6967
6968     // We need to round trip through the appropriate type for the shift.
6969     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6970     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6971     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6972            "Illegal integer vector type");
6973     V = DAG.getBitcast(ShiftVT, V);
6974
6975     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6976                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6977     return DAG.getBitcast(VT, V);
6978   };
6979
6980   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6981   // keep doubling the size of the integer elements up to that. We can
6982   // then shift the elements of the integer vector by whole multiples of
6983   // their width within the elements of the larger integer vector. Test each
6984   // multiple to see if we can find a match with the moved element indices
6985   // and that the shifted in elements are all zeroable.
6986   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6987     for (int Shift = 1; Shift != Scale; ++Shift)
6988       for (bool Left : {true, false})
6989         if (CheckZeros(Shift, Scale, Left))
6990           for (SDValue V : {V1, V2})
6991             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6992               return Match;
6993
6994   // no match
6995   return SDValue();
6996 }
6997
6998 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6999 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7000                                            SDValue V2, ArrayRef<int> Mask,
7001                                            SelectionDAG &DAG) {
7002   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7003   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7004
7005   int Size = Mask.size();
7006   int HalfSize = Size / 2;
7007   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7008
7009   // Upper half must be undefined.
7010   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7011     return SDValue();
7012
7013   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7014   // Remainder of lower half result is zero and upper half is all undef.
7015   auto LowerAsEXTRQ = [&]() {
7016     // Determine the extraction length from the part of the
7017     // lower half that isn't zeroable.
7018     int Len = HalfSize;
7019     for (; Len >= 0; --Len)
7020       if (!Zeroable[Len - 1])
7021         break;
7022     assert(Len > 0 && "Zeroable shuffle mask");
7023
7024     // Attempt to match first Len sequential elements from the lower half.
7025     SDValue Src;
7026     int Idx = -1;
7027     for (int i = 0; i != Len; ++i) {
7028       int M = Mask[i];
7029       if (M < 0)
7030         continue;
7031       SDValue &V = (M < Size ? V1 : V2);
7032       M = M % Size;
7033
7034       // All mask elements must be in the lower half.
7035       if (M > HalfSize)
7036         return SDValue();
7037
7038       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7039         Src = V;
7040         Idx = M - i;
7041         continue;
7042       }
7043       return SDValue();
7044     }
7045
7046     if (Idx < 0)
7047       return SDValue();
7048
7049     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7050     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7051     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7052     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7053                        DAG.getConstant(BitLen, DL, MVT::i8),
7054                        DAG.getConstant(BitIdx, DL, MVT::i8));
7055   };
7056
7057   if (SDValue ExtrQ = LowerAsEXTRQ())
7058     return ExtrQ;
7059
7060   // INSERTQ: Extract lowest Len elements from lower half of second source and
7061   // insert over first source, starting at Idx.
7062   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7063   auto LowerAsInsertQ = [&]() {
7064     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7065       SDValue Base;
7066
7067       // Attempt to match first source from mask before insertion point.
7068       if (isUndefInRange(Mask, 0, Idx)) {
7069         /* EMPTY */
7070       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7071         Base = V1;
7072       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7073         Base = V2;
7074       } else {
7075         continue;
7076       }
7077
7078       // Extend the extraction length looking to match both the insertion of
7079       // the second source and the remaining elements of the first.
7080       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7081         SDValue Insert;
7082         int Len = Hi - Idx;
7083
7084         // Match insertion.
7085         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7086           Insert = V1;
7087         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7088           Insert = V2;
7089         } else {
7090           continue;
7091         }
7092
7093         // Match the remaining elements of the lower half.
7094         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7095           /* EMPTY */
7096         } else if ((!Base || (Base == V1)) &&
7097                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7098           Base = V1;
7099         } else if ((!Base || (Base == V2)) &&
7100                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7101                                               Size + Hi)) {
7102           Base = V2;
7103         } else {
7104           continue;
7105         }
7106
7107         // We may not have a base (first source) - this can safely be undefined.
7108         if (!Base)
7109           Base = DAG.getUNDEF(VT);
7110
7111         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7112         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7113         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7114                            DAG.getConstant(BitLen, DL, MVT::i8),
7115                            DAG.getConstant(BitIdx, DL, MVT::i8));
7116       }
7117     }
7118
7119     return SDValue();
7120   };
7121
7122   if (SDValue InsertQ = LowerAsInsertQ())
7123     return InsertQ;
7124
7125   return SDValue();
7126 }
7127
7128 /// \brief Lower a vector shuffle as a zero or any extension.
7129 ///
7130 /// Given a specific number of elements, element bit width, and extension
7131 /// stride, produce either a zero or any extension based on the available
7132 /// features of the subtarget.
7133 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7134     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7135     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7136   assert(Scale > 1 && "Need a scale to extend.");
7137   int NumElements = VT.getVectorNumElements();
7138   int EltBits = VT.getScalarSizeInBits();
7139   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7140          "Only 8, 16, and 32 bit elements can be extended.");
7141   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7142
7143   // Found a valid zext mask! Try various lowering strategies based on the
7144   // input type and available ISA extensions.
7145   if (Subtarget->hasSSE41()) {
7146     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7147                                  NumElements / Scale);
7148     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7149   }
7150
7151   // For any extends we can cheat for larger element sizes and use shuffle
7152   // instructions that can fold with a load and/or copy.
7153   if (AnyExt && EltBits == 32) {
7154     int PSHUFDMask[4] = {0, -1, 1, -1};
7155     return DAG.getBitcast(
7156         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7157                         DAG.getBitcast(MVT::v4i32, InputV),
7158                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7159   }
7160   if (AnyExt && EltBits == 16 && Scale > 2) {
7161     int PSHUFDMask[4] = {0, -1, 0, -1};
7162     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7163                          DAG.getBitcast(MVT::v4i32, InputV),
7164                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7165     int PSHUFHWMask[4] = {1, -1, -1, -1};
7166     return DAG.getBitcast(
7167         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7168                         DAG.getBitcast(MVT::v8i16, InputV),
7169                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7170   }
7171
7172   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7173   // to 64-bits.
7174   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7175     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7176     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7177
7178     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7179                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7180                                          DAG.getConstant(EltBits, DL, MVT::i8),
7181                                          DAG.getConstant(0, DL, MVT::i8)));
7182     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7183       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7184
7185     SDValue Hi =
7186         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7187                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7188                                 DAG.getConstant(EltBits, DL, MVT::i8),
7189                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7190     return DAG.getNode(ISD::BITCAST, DL, VT,
7191                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7192   }
7193
7194   // If this would require more than 2 unpack instructions to expand, use
7195   // pshufb when available. We can only use more than 2 unpack instructions
7196   // when zero extending i8 elements which also makes it easier to use pshufb.
7197   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7198     assert(NumElements == 16 && "Unexpected byte vector width!");
7199     SDValue PSHUFBMask[16];
7200     for (int i = 0; i < 16; ++i)
7201       PSHUFBMask[i] =
7202           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7203     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7204     return DAG.getBitcast(VT,
7205                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7206                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7207                                                   MVT::v16i8, PSHUFBMask)));
7208   }
7209
7210   // Otherwise emit a sequence of unpacks.
7211   do {
7212     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7213     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7214                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7215     InputV = DAG.getBitcast(InputVT, InputV);
7216     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7217     Scale /= 2;
7218     EltBits *= 2;
7219     NumElements /= 2;
7220   } while (Scale > 1);
7221   return DAG.getBitcast(VT, InputV);
7222 }
7223
7224 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7225 ///
7226 /// This routine will try to do everything in its power to cleverly lower
7227 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7228 /// check for the profitability of this lowering,  it tries to aggressively
7229 /// match this pattern. It will use all of the micro-architectural details it
7230 /// can to emit an efficient lowering. It handles both blends with all-zero
7231 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7232 /// masking out later).
7233 ///
7234 /// The reason we have dedicated lowering for zext-style shuffles is that they
7235 /// are both incredibly common and often quite performance sensitive.
7236 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7237     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7238     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7239   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7240
7241   int Bits = VT.getSizeInBits();
7242   int NumElements = VT.getVectorNumElements();
7243   assert(VT.getScalarSizeInBits() <= 32 &&
7244          "Exceeds 32-bit integer zero extension limit");
7245   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7246
7247   // Define a helper function to check a particular ext-scale and lower to it if
7248   // valid.
7249   auto Lower = [&](int Scale) -> SDValue {
7250     SDValue InputV;
7251     bool AnyExt = true;
7252     for (int i = 0; i < NumElements; ++i) {
7253       if (Mask[i] == -1)
7254         continue; // Valid anywhere but doesn't tell us anything.
7255       if (i % Scale != 0) {
7256         // Each of the extended elements need to be zeroable.
7257         if (!Zeroable[i])
7258           return SDValue();
7259
7260         // We no longer are in the anyext case.
7261         AnyExt = false;
7262         continue;
7263       }
7264
7265       // Each of the base elements needs to be consecutive indices into the
7266       // same input vector.
7267       SDValue V = Mask[i] < NumElements ? V1 : V2;
7268       if (!InputV)
7269         InputV = V;
7270       else if (InputV != V)
7271         return SDValue(); // Flip-flopping inputs.
7272
7273       if (Mask[i] % NumElements != i / Scale)
7274         return SDValue(); // Non-consecutive strided elements.
7275     }
7276
7277     // If we fail to find an input, we have a zero-shuffle which should always
7278     // have already been handled.
7279     // FIXME: Maybe handle this here in case during blending we end up with one?
7280     if (!InputV)
7281       return SDValue();
7282
7283     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7284         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7285   };
7286
7287   // The widest scale possible for extending is to a 64-bit integer.
7288   assert(Bits % 64 == 0 &&
7289          "The number of bits in a vector must be divisible by 64 on x86!");
7290   int NumExtElements = Bits / 64;
7291
7292   // Each iteration, try extending the elements half as much, but into twice as
7293   // many elements.
7294   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7295     assert(NumElements % NumExtElements == 0 &&
7296            "The input vector size must be divisible by the extended size.");
7297     if (SDValue V = Lower(NumElements / NumExtElements))
7298       return V;
7299   }
7300
7301   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7302   if (Bits != 128)
7303     return SDValue();
7304
7305   // Returns one of the source operands if the shuffle can be reduced to a
7306   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7307   auto CanZExtLowHalf = [&]() {
7308     for (int i = NumElements / 2; i != NumElements; ++i)
7309       if (!Zeroable[i])
7310         return SDValue();
7311     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7312       return V1;
7313     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7314       return V2;
7315     return SDValue();
7316   };
7317
7318   if (SDValue V = CanZExtLowHalf()) {
7319     V = DAG.getBitcast(MVT::v2i64, V);
7320     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7321     return DAG.getBitcast(VT, V);
7322   }
7323
7324   // No viable ext lowering found.
7325   return SDValue();
7326 }
7327
7328 /// \brief Try to get a scalar value for a specific element of a vector.
7329 ///
7330 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7331 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7332                                               SelectionDAG &DAG) {
7333   MVT VT = V.getSimpleValueType();
7334   MVT EltVT = VT.getVectorElementType();
7335   while (V.getOpcode() == ISD::BITCAST)
7336     V = V.getOperand(0);
7337   // If the bitcasts shift the element size, we can't extract an equivalent
7338   // element from it.
7339   MVT NewVT = V.getSimpleValueType();
7340   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7341     return SDValue();
7342
7343   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7344       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7345     // Ensure the scalar operand is the same size as the destination.
7346     // FIXME: Add support for scalar truncation where possible.
7347     SDValue S = V.getOperand(Idx);
7348     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7349       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7350   }
7351
7352   return SDValue();
7353 }
7354
7355 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7356 ///
7357 /// This is particularly important because the set of instructions varies
7358 /// significantly based on whether the operand is a load or not.
7359 static bool isShuffleFoldableLoad(SDValue V) {
7360   while (V.getOpcode() == ISD::BITCAST)
7361     V = V.getOperand(0);
7362
7363   return ISD::isNON_EXTLoad(V.getNode());
7364 }
7365
7366 /// \brief Try to lower insertion of a single element into a zero vector.
7367 ///
7368 /// This is a common pattern that we have especially efficient patterns to lower
7369 /// across all subtarget feature sets.
7370 static SDValue lowerVectorShuffleAsElementInsertion(
7371     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7372     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7373   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7374   MVT ExtVT = VT;
7375   MVT EltVT = VT.getVectorElementType();
7376
7377   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7378                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7379                 Mask.begin();
7380   bool IsV1Zeroable = true;
7381   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7382     if (i != V2Index && !Zeroable[i]) {
7383       IsV1Zeroable = false;
7384       break;
7385     }
7386
7387   // Check for a single input from a SCALAR_TO_VECTOR node.
7388   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7389   // all the smarts here sunk into that routine. However, the current
7390   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7391   // vector shuffle lowering is dead.
7392   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7393                                                DAG);
7394   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7395     // We need to zext the scalar if it is smaller than an i32.
7396     V2S = DAG.getBitcast(EltVT, V2S);
7397     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7398       // Using zext to expand a narrow element won't work for non-zero
7399       // insertions.
7400       if (!IsV1Zeroable)
7401         return SDValue();
7402
7403       // Zero-extend directly to i32.
7404       ExtVT = MVT::v4i32;
7405       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7406     }
7407     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7408   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7409              EltVT == MVT::i16) {
7410     // Either not inserting from the low element of the input or the input
7411     // element size is too small to use VZEXT_MOVL to clear the high bits.
7412     return SDValue();
7413   }
7414
7415   if (!IsV1Zeroable) {
7416     // If V1 can't be treated as a zero vector we have fewer options to lower
7417     // this. We can't support integer vectors or non-zero targets cheaply, and
7418     // the V1 elements can't be permuted in any way.
7419     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7420     if (!VT.isFloatingPoint() || V2Index != 0)
7421       return SDValue();
7422     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7423     V1Mask[V2Index] = -1;
7424     if (!isNoopShuffleMask(V1Mask))
7425       return SDValue();
7426     // This is essentially a special case blend operation, but if we have
7427     // general purpose blend operations, they are always faster. Bail and let
7428     // the rest of the lowering handle these as blends.
7429     if (Subtarget->hasSSE41())
7430       return SDValue();
7431
7432     // Otherwise, use MOVSD or MOVSS.
7433     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7434            "Only two types of floating point element types to handle!");
7435     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7436                        ExtVT, V1, V2);
7437   }
7438
7439   // This lowering only works for the low element with floating point vectors.
7440   if (VT.isFloatingPoint() && V2Index != 0)
7441     return SDValue();
7442
7443   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7444   if (ExtVT != VT)
7445     V2 = DAG.getBitcast(VT, V2);
7446
7447   if (V2Index != 0) {
7448     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7449     // the desired position. Otherwise it is more efficient to do a vector
7450     // shift left. We know that we can do a vector shift left because all
7451     // the inputs are zero.
7452     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7453       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7454       V2Shuffle[V2Index] = 0;
7455       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7456     } else {
7457       V2 = DAG.getBitcast(MVT::v2i64, V2);
7458       V2 = DAG.getNode(
7459           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7460           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7461                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7462                               DAG.getDataLayout(), VT)));
7463       V2 = DAG.getBitcast(VT, V2);
7464     }
7465   }
7466   return V2;
7467 }
7468
7469 /// \brief Try to lower broadcast of a single element.
7470 ///
7471 /// For convenience, this code also bundles all of the subtarget feature set
7472 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7473 /// a convenient way to factor it out.
7474 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7475                                              ArrayRef<int> Mask,
7476                                              const X86Subtarget *Subtarget,
7477                                              SelectionDAG &DAG) {
7478   if (!Subtarget->hasAVX())
7479     return SDValue();
7480   if (VT.isInteger() && !Subtarget->hasAVX2())
7481     return SDValue();
7482
7483   // Check that the mask is a broadcast.
7484   int BroadcastIdx = -1;
7485   for (int M : Mask)
7486     if (M >= 0 && BroadcastIdx == -1)
7487       BroadcastIdx = M;
7488     else if (M >= 0 && M != BroadcastIdx)
7489       return SDValue();
7490
7491   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7492                                             "a sorted mask where the broadcast "
7493                                             "comes from V1.");
7494
7495   // Go up the chain of (vector) values to find a scalar load that we can
7496   // combine with the broadcast.
7497   for (;;) {
7498     switch (V.getOpcode()) {
7499     case ISD::CONCAT_VECTORS: {
7500       int OperandSize = Mask.size() / V.getNumOperands();
7501       V = V.getOperand(BroadcastIdx / OperandSize);
7502       BroadcastIdx %= OperandSize;
7503       continue;
7504     }
7505
7506     case ISD::INSERT_SUBVECTOR: {
7507       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7508       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7509       if (!ConstantIdx)
7510         break;
7511
7512       int BeginIdx = (int)ConstantIdx->getZExtValue();
7513       int EndIdx =
7514           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7515       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7516         BroadcastIdx -= BeginIdx;
7517         V = VInner;
7518       } else {
7519         V = VOuter;
7520       }
7521       continue;
7522     }
7523     }
7524     break;
7525   }
7526
7527   // Check if this is a broadcast of a scalar. We special case lowering
7528   // for scalars so that we can more effectively fold with loads.
7529   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7530       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7531     V = V.getOperand(BroadcastIdx);
7532
7533     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7534     // Only AVX2 has register broadcasts.
7535     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7536       return SDValue();
7537   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7538     // We can't broadcast from a vector register without AVX2, and we can only
7539     // broadcast from the zero-element of a vector register.
7540     return SDValue();
7541   }
7542
7543   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7544 }
7545
7546 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7547 // INSERTPS when the V1 elements are already in the correct locations
7548 // because otherwise we can just always use two SHUFPS instructions which
7549 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7550 // perform INSERTPS if a single V1 element is out of place and all V2
7551 // elements are zeroable.
7552 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7553                                             ArrayRef<int> Mask,
7554                                             SelectionDAG &DAG) {
7555   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7556   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7557   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7558   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7559
7560   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7561
7562   unsigned ZMask = 0;
7563   int V1DstIndex = -1;
7564   int V2DstIndex = -1;
7565   bool V1UsedInPlace = false;
7566
7567   for (int i = 0; i < 4; ++i) {
7568     // Synthesize a zero mask from the zeroable elements (includes undefs).
7569     if (Zeroable[i]) {
7570       ZMask |= 1 << i;
7571       continue;
7572     }
7573
7574     // Flag if we use any V1 inputs in place.
7575     if (i == Mask[i]) {
7576       V1UsedInPlace = true;
7577       continue;
7578     }
7579
7580     // We can only insert a single non-zeroable element.
7581     if (V1DstIndex != -1 || V2DstIndex != -1)
7582       return SDValue();
7583
7584     if (Mask[i] < 4) {
7585       // V1 input out of place for insertion.
7586       V1DstIndex = i;
7587     } else {
7588       // V2 input for insertion.
7589       V2DstIndex = i;
7590     }
7591   }
7592
7593   // Don't bother if we have no (non-zeroable) element for insertion.
7594   if (V1DstIndex == -1 && V2DstIndex == -1)
7595     return SDValue();
7596
7597   // Determine element insertion src/dst indices. The src index is from the
7598   // start of the inserted vector, not the start of the concatenated vector.
7599   unsigned V2SrcIndex = 0;
7600   if (V1DstIndex != -1) {
7601     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7602     // and don't use the original V2 at all.
7603     V2SrcIndex = Mask[V1DstIndex];
7604     V2DstIndex = V1DstIndex;
7605     V2 = V1;
7606   } else {
7607     V2SrcIndex = Mask[V2DstIndex] - 4;
7608   }
7609
7610   // If no V1 inputs are used in place, then the result is created only from
7611   // the zero mask and the V2 insertion - so remove V1 dependency.
7612   if (!V1UsedInPlace)
7613     V1 = DAG.getUNDEF(MVT::v4f32);
7614
7615   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7616   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7617
7618   // Insert the V2 element into the desired position.
7619   SDLoc DL(Op);
7620   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7621                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7622 }
7623
7624 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7625 /// UNPCK instruction.
7626 ///
7627 /// This specifically targets cases where we end up with alternating between
7628 /// the two inputs, and so can permute them into something that feeds a single
7629 /// UNPCK instruction. Note that this routine only targets integer vectors
7630 /// because for floating point vectors we have a generalized SHUFPS lowering
7631 /// strategy that handles everything that doesn't *exactly* match an unpack,
7632 /// making this clever lowering unnecessary.
7633 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7634                                           SDValue V2, ArrayRef<int> Mask,
7635                                           SelectionDAG &DAG) {
7636   assert(!VT.isFloatingPoint() &&
7637          "This routine only supports integer vectors.");
7638   assert(!isSingleInputShuffleMask(Mask) &&
7639          "This routine should only be used when blending two inputs.");
7640   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7641
7642   int Size = Mask.size();
7643
7644   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7645     return M >= 0 && M % Size < Size / 2;
7646   });
7647   int NumHiInputs = std::count_if(
7648       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7649
7650   bool UnpackLo = NumLoInputs >= NumHiInputs;
7651
7652   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7653     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7654     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7655
7656     for (int i = 0; i < Size; ++i) {
7657       if (Mask[i] < 0)
7658         continue;
7659
7660       // Each element of the unpack contains Scale elements from this mask.
7661       int UnpackIdx = i / Scale;
7662
7663       // We only handle the case where V1 feeds the first slots of the unpack.
7664       // We rely on canonicalization to ensure this is the case.
7665       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7666         return SDValue();
7667
7668       // Setup the mask for this input. The indexing is tricky as we have to
7669       // handle the unpack stride.
7670       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7671       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7672           Mask[i] % Size;
7673     }
7674
7675     // If we will have to shuffle both inputs to use the unpack, check whether
7676     // we can just unpack first and shuffle the result. If so, skip this unpack.
7677     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7678         !isNoopShuffleMask(V2Mask))
7679       return SDValue();
7680
7681     // Shuffle the inputs into place.
7682     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7683     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7684
7685     // Cast the inputs to the type we will use to unpack them.
7686     V1 = DAG.getBitcast(UnpackVT, V1);
7687     V2 = DAG.getBitcast(UnpackVT, V2);
7688
7689     // Unpack the inputs and cast the result back to the desired type.
7690     return DAG.getBitcast(
7691         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7692                         UnpackVT, V1, V2));
7693   };
7694
7695   // We try each unpack from the largest to the smallest to try and find one
7696   // that fits this mask.
7697   int OrigNumElements = VT.getVectorNumElements();
7698   int OrigScalarSize = VT.getScalarSizeInBits();
7699   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7700     int Scale = ScalarSize / OrigScalarSize;
7701     int NumElements = OrigNumElements / Scale;
7702     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7703     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7704       return Unpack;
7705   }
7706
7707   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7708   // initial unpack.
7709   if (NumLoInputs == 0 || NumHiInputs == 0) {
7710     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7711            "We have to have *some* inputs!");
7712     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7713
7714     // FIXME: We could consider the total complexity of the permute of each
7715     // possible unpacking. Or at the least we should consider how many
7716     // half-crossings are created.
7717     // FIXME: We could consider commuting the unpacks.
7718
7719     SmallVector<int, 32> PermMask;
7720     PermMask.assign(Size, -1);
7721     for (int i = 0; i < Size; ++i) {
7722       if (Mask[i] < 0)
7723         continue;
7724
7725       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7726
7727       PermMask[i] =
7728           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7729     }
7730     return DAG.getVectorShuffle(
7731         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7732                             DL, VT, V1, V2),
7733         DAG.getUNDEF(VT), PermMask);
7734   }
7735
7736   return SDValue();
7737 }
7738
7739 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7740 ///
7741 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7742 /// support for floating point shuffles but not integer shuffles. These
7743 /// instructions will incur a domain crossing penalty on some chips though so
7744 /// it is better to avoid lowering through this for integer vectors where
7745 /// possible.
7746 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7747                                        const X86Subtarget *Subtarget,
7748                                        SelectionDAG &DAG) {
7749   SDLoc DL(Op);
7750   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7751   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7752   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7753   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7754   ArrayRef<int> Mask = SVOp->getMask();
7755   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7756
7757   if (isSingleInputShuffleMask(Mask)) {
7758     // Use low duplicate instructions for masks that match their pattern.
7759     if (Subtarget->hasSSE3())
7760       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7761         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7762
7763     // Straight shuffle of a single input vector. Simulate this by using the
7764     // single input as both of the "inputs" to this instruction..
7765     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7766
7767     if (Subtarget->hasAVX()) {
7768       // If we have AVX, we can use VPERMILPS which will allow folding a load
7769       // into the shuffle.
7770       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7771                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7772     }
7773
7774     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7775                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7776   }
7777   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7778   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7779
7780   // If we have a single input, insert that into V1 if we can do so cheaply.
7781   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7782     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7783             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7784       return Insertion;
7785     // Try inverting the insertion since for v2 masks it is easy to do and we
7786     // can't reliably sort the mask one way or the other.
7787     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7788                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7789     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7790             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7791       return Insertion;
7792   }
7793
7794   // Try to use one of the special instruction patterns to handle two common
7795   // blend patterns if a zero-blend above didn't work.
7796   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7797       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7798     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7799       // We can either use a special instruction to load over the low double or
7800       // to move just the low double.
7801       return DAG.getNode(
7802           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7803           DL, MVT::v2f64, V2,
7804           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7805
7806   if (Subtarget->hasSSE41())
7807     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7808                                                   Subtarget, DAG))
7809       return Blend;
7810
7811   // Use dedicated unpack instructions for masks that match their pattern.
7812   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7813     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7814   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7815     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7816
7817   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7818   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7819                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7820 }
7821
7822 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7823 ///
7824 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7825 /// the integer unit to minimize domain crossing penalties. However, for blends
7826 /// it falls back to the floating point shuffle operation with appropriate bit
7827 /// casting.
7828 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7829                                        const X86Subtarget *Subtarget,
7830                                        SelectionDAG &DAG) {
7831   SDLoc DL(Op);
7832   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7833   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7834   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7835   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7836   ArrayRef<int> Mask = SVOp->getMask();
7837   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7838
7839   if (isSingleInputShuffleMask(Mask)) {
7840     // Check for being able to broadcast a single element.
7841     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7842                                                           Mask, Subtarget, DAG))
7843       return Broadcast;
7844
7845     // Straight shuffle of a single input vector. For everything from SSE2
7846     // onward this has a single fast instruction with no scary immediates.
7847     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7848     V1 = DAG.getBitcast(MVT::v4i32, V1);
7849     int WidenedMask[4] = {
7850         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7851         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7852     return DAG.getBitcast(
7853         MVT::v2i64,
7854         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7855                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7856   }
7857   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7858   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7859   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7860   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7861
7862   // If we have a blend of two PACKUS operations an the blend aligns with the
7863   // low and half halves, we can just merge the PACKUS operations. This is
7864   // particularly important as it lets us merge shuffles that this routine itself
7865   // creates.
7866   auto GetPackNode = [](SDValue V) {
7867     while (V.getOpcode() == ISD::BITCAST)
7868       V = V.getOperand(0);
7869
7870     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7871   };
7872   if (SDValue V1Pack = GetPackNode(V1))
7873     if (SDValue V2Pack = GetPackNode(V2))
7874       return DAG.getBitcast(MVT::v2i64,
7875                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7876                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7877                                                      : V1Pack.getOperand(1),
7878                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7879                                                      : V2Pack.getOperand(1)));
7880
7881   // Try to use shift instructions.
7882   if (SDValue Shift =
7883           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7884     return Shift;
7885
7886   // When loading a scalar and then shuffling it into a vector we can often do
7887   // the insertion cheaply.
7888   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7889           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7890     return Insertion;
7891   // Try inverting the insertion since for v2 masks it is easy to do and we
7892   // can't reliably sort the mask one way or the other.
7893   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7894   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7895           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7896     return Insertion;
7897
7898   // We have different paths for blend lowering, but they all must use the
7899   // *exact* same predicate.
7900   bool IsBlendSupported = Subtarget->hasSSE41();
7901   if (IsBlendSupported)
7902     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7903                                                   Subtarget, DAG))
7904       return Blend;
7905
7906   // Use dedicated unpack instructions for masks that match their pattern.
7907   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7908     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7909   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7910     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7911
7912   // Try to use byte rotation instructions.
7913   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7914   if (Subtarget->hasSSSE3())
7915     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7916             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7917       return Rotate;
7918
7919   // If we have direct support for blends, we should lower by decomposing into
7920   // a permute. That will be faster than the domain cross.
7921   if (IsBlendSupported)
7922     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7923                                                       Mask, DAG);
7924
7925   // We implement this with SHUFPD which is pretty lame because it will likely
7926   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7927   // However, all the alternatives are still more cycles and newer chips don't
7928   // have this problem. It would be really nice if x86 had better shuffles here.
7929   V1 = DAG.getBitcast(MVT::v2f64, V1);
7930   V2 = DAG.getBitcast(MVT::v2f64, V2);
7931   return DAG.getBitcast(MVT::v2i64,
7932                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7933 }
7934
7935 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7936 ///
7937 /// This is used to disable more specialized lowerings when the shufps lowering
7938 /// will happen to be efficient.
7939 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7940   // This routine only handles 128-bit shufps.
7941   assert(Mask.size() == 4 && "Unsupported mask size!");
7942
7943   // To lower with a single SHUFPS we need to have the low half and high half
7944   // each requiring a single input.
7945   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7946     return false;
7947   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7948     return false;
7949
7950   return true;
7951 }
7952
7953 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7954 ///
7955 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7956 /// It makes no assumptions about whether this is the *best* lowering, it simply
7957 /// uses it.
7958 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7959                                             ArrayRef<int> Mask, SDValue V1,
7960                                             SDValue V2, SelectionDAG &DAG) {
7961   SDValue LowV = V1, HighV = V2;
7962   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7963
7964   int NumV2Elements =
7965       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7966
7967   if (NumV2Elements == 1) {
7968     int V2Index =
7969         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7970         Mask.begin();
7971
7972     // Compute the index adjacent to V2Index and in the same half by toggling
7973     // the low bit.
7974     int V2AdjIndex = V2Index ^ 1;
7975
7976     if (Mask[V2AdjIndex] == -1) {
7977       // Handles all the cases where we have a single V2 element and an undef.
7978       // This will only ever happen in the high lanes because we commute the
7979       // vector otherwise.
7980       if (V2Index < 2)
7981         std::swap(LowV, HighV);
7982       NewMask[V2Index] -= 4;
7983     } else {
7984       // Handle the case where the V2 element ends up adjacent to a V1 element.
7985       // To make this work, blend them together as the first step.
7986       int V1Index = V2AdjIndex;
7987       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7988       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7989                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7990
7991       // Now proceed to reconstruct the final blend as we have the necessary
7992       // high or low half formed.
7993       if (V2Index < 2) {
7994         LowV = V2;
7995         HighV = V1;
7996       } else {
7997         HighV = V2;
7998       }
7999       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8000       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8001     }
8002   } else if (NumV2Elements == 2) {
8003     if (Mask[0] < 4 && Mask[1] < 4) {
8004       // Handle the easy case where we have V1 in the low lanes and V2 in the
8005       // high lanes.
8006       NewMask[2] -= 4;
8007       NewMask[3] -= 4;
8008     } else if (Mask[2] < 4 && Mask[3] < 4) {
8009       // We also handle the reversed case because this utility may get called
8010       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8011       // arrange things in the right direction.
8012       NewMask[0] -= 4;
8013       NewMask[1] -= 4;
8014       HighV = V1;
8015       LowV = V2;
8016     } else {
8017       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8018       // trying to place elements directly, just blend them and set up the final
8019       // shuffle to place them.
8020
8021       // The first two blend mask elements are for V1, the second two are for
8022       // V2.
8023       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8024                           Mask[2] < 4 ? Mask[2] : Mask[3],
8025                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8026                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8027       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8028                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8029
8030       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8031       // a blend.
8032       LowV = HighV = V1;
8033       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8034       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8035       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8036       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8037     }
8038   }
8039   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8040                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8041 }
8042
8043 /// \brief Lower 4-lane 32-bit floating point shuffles.
8044 ///
8045 /// Uses instructions exclusively from the floating point unit to minimize
8046 /// domain crossing penalties, as these are sufficient to implement all v4f32
8047 /// shuffles.
8048 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8049                                        const X86Subtarget *Subtarget,
8050                                        SelectionDAG &DAG) {
8051   SDLoc DL(Op);
8052   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8053   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8054   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8055   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8056   ArrayRef<int> Mask = SVOp->getMask();
8057   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8058
8059   int NumV2Elements =
8060       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8061
8062   if (NumV2Elements == 0) {
8063     // Check for being able to broadcast a single element.
8064     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8065                                                           Mask, Subtarget, DAG))
8066       return Broadcast;
8067
8068     // Use even/odd duplicate instructions for masks that match their pattern.
8069     if (Subtarget->hasSSE3()) {
8070       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8071         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8072       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8073         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8074     }
8075
8076     if (Subtarget->hasAVX()) {
8077       // If we have AVX, we can use VPERMILPS which will allow folding a load
8078       // into the shuffle.
8079       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8080                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8081     }
8082
8083     // Otherwise, use a straight shuffle of a single input vector. We pass the
8084     // input vector to both operands to simulate this with a SHUFPS.
8085     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8086                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8087   }
8088
8089   // There are special ways we can lower some single-element blends. However, we
8090   // have custom ways we can lower more complex single-element blends below that
8091   // we defer to if both this and BLENDPS fail to match, so restrict this to
8092   // when the V2 input is targeting element 0 of the mask -- that is the fast
8093   // case here.
8094   if (NumV2Elements == 1 && Mask[0] >= 4)
8095     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8096                                                          Mask, Subtarget, DAG))
8097       return V;
8098
8099   if (Subtarget->hasSSE41()) {
8100     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8101                                                   Subtarget, DAG))
8102       return Blend;
8103
8104     // Use INSERTPS if we can complete the shuffle efficiently.
8105     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8106       return V;
8107
8108     if (!isSingleSHUFPSMask(Mask))
8109       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8110               DL, MVT::v4f32, V1, V2, Mask, DAG))
8111         return BlendPerm;
8112   }
8113
8114   // Use dedicated unpack instructions for masks that match their pattern.
8115   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8116     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8117   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8118     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8119   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8120     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8121   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8122     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8123
8124   // Otherwise fall back to a SHUFPS lowering strategy.
8125   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8126 }
8127
8128 /// \brief Lower 4-lane i32 vector shuffles.
8129 ///
8130 /// We try to handle these with integer-domain shuffles where we can, but for
8131 /// blends we use the floating point domain blend instructions.
8132 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8133                                        const X86Subtarget *Subtarget,
8134                                        SelectionDAG &DAG) {
8135   SDLoc DL(Op);
8136   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8137   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8138   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8139   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8140   ArrayRef<int> Mask = SVOp->getMask();
8141   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8142
8143   // Whenever we can lower this as a zext, that instruction is strictly faster
8144   // than any alternative. It also allows us to fold memory operands into the
8145   // shuffle in many cases.
8146   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8147                                                          Mask, Subtarget, DAG))
8148     return ZExt;
8149
8150   int NumV2Elements =
8151       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8152
8153   if (NumV2Elements == 0) {
8154     // Check for being able to broadcast a single element.
8155     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8156                                                           Mask, Subtarget, DAG))
8157       return Broadcast;
8158
8159     // Straight shuffle of a single input vector. For everything from SSE2
8160     // onward this has a single fast instruction with no scary immediates.
8161     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8162     // but we aren't actually going to use the UNPCK instruction because doing
8163     // so prevents folding a load into this instruction or making a copy.
8164     const int UnpackLoMask[] = {0, 0, 1, 1};
8165     const int UnpackHiMask[] = {2, 2, 3, 3};
8166     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8167       Mask = UnpackLoMask;
8168     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8169       Mask = UnpackHiMask;
8170
8171     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8172                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8173   }
8174
8175   // Try to use shift instructions.
8176   if (SDValue Shift =
8177           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8178     return Shift;
8179
8180   // There are special ways we can lower some single-element blends.
8181   if (NumV2Elements == 1)
8182     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8183                                                          Mask, Subtarget, DAG))
8184       return V;
8185
8186   // We have different paths for blend lowering, but they all must use the
8187   // *exact* same predicate.
8188   bool IsBlendSupported = Subtarget->hasSSE41();
8189   if (IsBlendSupported)
8190     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8191                                                   Subtarget, DAG))
8192       return Blend;
8193
8194   if (SDValue Masked =
8195           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8196     return Masked;
8197
8198   // Use dedicated unpack instructions for masks that match their pattern.
8199   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8200     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8201   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8202     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8203   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8204     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8205   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8206     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8207
8208   // Try to use byte rotation instructions.
8209   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8210   if (Subtarget->hasSSSE3())
8211     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8212             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8213       return Rotate;
8214
8215   // If we have direct support for blends, we should lower by decomposing into
8216   // a permute. That will be faster than the domain cross.
8217   if (IsBlendSupported)
8218     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8219                                                       Mask, DAG);
8220
8221   // Try to lower by permuting the inputs into an unpack instruction.
8222   if (SDValue Unpack =
8223           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8224     return Unpack;
8225
8226   // We implement this with SHUFPS because it can blend from two vectors.
8227   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8228   // up the inputs, bypassing domain shift penalties that we would encur if we
8229   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8230   // relevant.
8231   return DAG.getBitcast(
8232       MVT::v4i32,
8233       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8234                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8235 }
8236
8237 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8238 /// shuffle lowering, and the most complex part.
8239 ///
8240 /// The lowering strategy is to try to form pairs of input lanes which are
8241 /// targeted at the same half of the final vector, and then use a dword shuffle
8242 /// to place them onto the right half, and finally unpack the paired lanes into
8243 /// their final position.
8244 ///
8245 /// The exact breakdown of how to form these dword pairs and align them on the
8246 /// correct sides is really tricky. See the comments within the function for
8247 /// more of the details.
8248 ///
8249 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8250 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8251 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8252 /// vector, form the analogous 128-bit 8-element Mask.
8253 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8254     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8255     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8256   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8257   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8258
8259   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8260   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8261   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8262
8263   SmallVector<int, 4> LoInputs;
8264   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8265                [](int M) { return M >= 0; });
8266   std::sort(LoInputs.begin(), LoInputs.end());
8267   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8268   SmallVector<int, 4> HiInputs;
8269   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8270                [](int M) { return M >= 0; });
8271   std::sort(HiInputs.begin(), HiInputs.end());
8272   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8273   int NumLToL =
8274       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8275   int NumHToL = LoInputs.size() - NumLToL;
8276   int NumLToH =
8277       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8278   int NumHToH = HiInputs.size() - NumLToH;
8279   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8280   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8281   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8282   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8283
8284   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8285   // such inputs we can swap two of the dwords across the half mark and end up
8286   // with <=2 inputs to each half in each half. Once there, we can fall through
8287   // to the generic code below. For example:
8288   //
8289   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8290   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8291   //
8292   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8293   // and an existing 2-into-2 on the other half. In this case we may have to
8294   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8295   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8296   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8297   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8298   // half than the one we target for fixing) will be fixed when we re-enter this
8299   // path. We will also combine away any sequence of PSHUFD instructions that
8300   // result into a single instruction. Here is an example of the tricky case:
8301   //
8302   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8303   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8304   //
8305   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8306   //
8307   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8308   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8309   //
8310   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8311   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8312   //
8313   // The result is fine to be handled by the generic logic.
8314   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8315                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8316                           int AOffset, int BOffset) {
8317     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8318            "Must call this with A having 3 or 1 inputs from the A half.");
8319     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8320            "Must call this with B having 1 or 3 inputs from the B half.");
8321     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8322            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8323
8324     // Compute the index of dword with only one word among the three inputs in
8325     // a half by taking the sum of the half with three inputs and subtracting
8326     // the sum of the actual three inputs. The difference is the remaining
8327     // slot.
8328     int ADWord, BDWord;
8329     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8330     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8331     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8332     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8333     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8334     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8335     int TripleNonInputIdx =
8336         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8337     TripleDWord = TripleNonInputIdx / 2;
8338
8339     // We use xor with one to compute the adjacent DWord to whichever one the
8340     // OneInput is in.
8341     OneInputDWord = (OneInput / 2) ^ 1;
8342
8343     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8344     // and BToA inputs. If there is also such a problem with the BToB and AToB
8345     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8346     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8347     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8348     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8349       // Compute how many inputs will be flipped by swapping these DWords. We
8350       // need
8351       // to balance this to ensure we don't form a 3-1 shuffle in the other
8352       // half.
8353       int NumFlippedAToBInputs =
8354           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8355           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8356       int NumFlippedBToBInputs =
8357           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8358           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8359       if ((NumFlippedAToBInputs == 1 &&
8360            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8361           (NumFlippedBToBInputs == 1 &&
8362            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8363         // We choose whether to fix the A half or B half based on whether that
8364         // half has zero flipped inputs. At zero, we may not be able to fix it
8365         // with that half. We also bias towards fixing the B half because that
8366         // will more commonly be the high half, and we have to bias one way.
8367         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8368                                                        ArrayRef<int> Inputs) {
8369           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8370           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8371                                          PinnedIdx ^ 1) != Inputs.end();
8372           // Determine whether the free index is in the flipped dword or the
8373           // unflipped dword based on where the pinned index is. We use this bit
8374           // in an xor to conditionally select the adjacent dword.
8375           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8376           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8377                                              FixFreeIdx) != Inputs.end();
8378           if (IsFixIdxInput == IsFixFreeIdxInput)
8379             FixFreeIdx += 1;
8380           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8381                                         FixFreeIdx) != Inputs.end();
8382           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8383                  "We need to be changing the number of flipped inputs!");
8384           int PSHUFHalfMask[] = {0, 1, 2, 3};
8385           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8386           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8387                           MVT::v8i16, V,
8388                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8389
8390           for (int &M : Mask)
8391             if (M != -1 && M == FixIdx)
8392               M = FixFreeIdx;
8393             else if (M != -1 && M == FixFreeIdx)
8394               M = FixIdx;
8395         };
8396         if (NumFlippedBToBInputs != 0) {
8397           int BPinnedIdx =
8398               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8399           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8400         } else {
8401           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8402           int APinnedIdx =
8403               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8404           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8405         }
8406       }
8407     }
8408
8409     int PSHUFDMask[] = {0, 1, 2, 3};
8410     PSHUFDMask[ADWord] = BDWord;
8411     PSHUFDMask[BDWord] = ADWord;
8412     V = DAG.getBitcast(
8413         VT,
8414         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8415                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8416
8417     // Adjust the mask to match the new locations of A and B.
8418     for (int &M : Mask)
8419       if (M != -1 && M/2 == ADWord)
8420         M = 2 * BDWord + M % 2;
8421       else if (M != -1 && M/2 == BDWord)
8422         M = 2 * ADWord + M % 2;
8423
8424     // Recurse back into this routine to re-compute state now that this isn't
8425     // a 3 and 1 problem.
8426     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8427                                                      DAG);
8428   };
8429   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8430     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8431   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8432     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8433
8434   // At this point there are at most two inputs to the low and high halves from
8435   // each half. That means the inputs can always be grouped into dwords and
8436   // those dwords can then be moved to the correct half with a dword shuffle.
8437   // We use at most one low and one high word shuffle to collect these paired
8438   // inputs into dwords, and finally a dword shuffle to place them.
8439   int PSHUFLMask[4] = {-1, -1, -1, -1};
8440   int PSHUFHMask[4] = {-1, -1, -1, -1};
8441   int PSHUFDMask[4] = {-1, -1, -1, -1};
8442
8443   // First fix the masks for all the inputs that are staying in their
8444   // original halves. This will then dictate the targets of the cross-half
8445   // shuffles.
8446   auto fixInPlaceInputs =
8447       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8448                     MutableArrayRef<int> SourceHalfMask,
8449                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8450     if (InPlaceInputs.empty())
8451       return;
8452     if (InPlaceInputs.size() == 1) {
8453       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8454           InPlaceInputs[0] - HalfOffset;
8455       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8456       return;
8457     }
8458     if (IncomingInputs.empty()) {
8459       // Just fix all of the in place inputs.
8460       for (int Input : InPlaceInputs) {
8461         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8462         PSHUFDMask[Input / 2] = Input / 2;
8463       }
8464       return;
8465     }
8466
8467     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8468     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8469         InPlaceInputs[0] - HalfOffset;
8470     // Put the second input next to the first so that they are packed into
8471     // a dword. We find the adjacent index by toggling the low bit.
8472     int AdjIndex = InPlaceInputs[0] ^ 1;
8473     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8474     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8475     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8476   };
8477   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8478   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8479
8480   // Now gather the cross-half inputs and place them into a free dword of
8481   // their target half.
8482   // FIXME: This operation could almost certainly be simplified dramatically to
8483   // look more like the 3-1 fixing operation.
8484   auto moveInputsToRightHalf = [&PSHUFDMask](
8485       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8486       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8487       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8488       int DestOffset) {
8489     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8490       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8491     };
8492     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8493                                                int Word) {
8494       int LowWord = Word & ~1;
8495       int HighWord = Word | 1;
8496       return isWordClobbered(SourceHalfMask, LowWord) ||
8497              isWordClobbered(SourceHalfMask, HighWord);
8498     };
8499
8500     if (IncomingInputs.empty())
8501       return;
8502
8503     if (ExistingInputs.empty()) {
8504       // Map any dwords with inputs from them into the right half.
8505       for (int Input : IncomingInputs) {
8506         // If the source half mask maps over the inputs, turn those into
8507         // swaps and use the swapped lane.
8508         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8509           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8510             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8511                 Input - SourceOffset;
8512             // We have to swap the uses in our half mask in one sweep.
8513             for (int &M : HalfMask)
8514               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8515                 M = Input;
8516               else if (M == Input)
8517                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8518           } else {
8519             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8520                        Input - SourceOffset &&
8521                    "Previous placement doesn't match!");
8522           }
8523           // Note that this correctly re-maps both when we do a swap and when
8524           // we observe the other side of the swap above. We rely on that to
8525           // avoid swapping the members of the input list directly.
8526           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8527         }
8528
8529         // Map the input's dword into the correct half.
8530         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8531           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8532         else
8533           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8534                      Input / 2 &&
8535                  "Previous placement doesn't match!");
8536       }
8537
8538       // And just directly shift any other-half mask elements to be same-half
8539       // as we will have mirrored the dword containing the element into the
8540       // same position within that half.
8541       for (int &M : HalfMask)
8542         if (M >= SourceOffset && M < SourceOffset + 4) {
8543           M = M - SourceOffset + DestOffset;
8544           assert(M >= 0 && "This should never wrap below zero!");
8545         }
8546       return;
8547     }
8548
8549     // Ensure we have the input in a viable dword of its current half. This
8550     // is particularly tricky because the original position may be clobbered
8551     // by inputs being moved and *staying* in that half.
8552     if (IncomingInputs.size() == 1) {
8553       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8554         int InputFixed = std::find(std::begin(SourceHalfMask),
8555                                    std::end(SourceHalfMask), -1) -
8556                          std::begin(SourceHalfMask) + SourceOffset;
8557         SourceHalfMask[InputFixed - SourceOffset] =
8558             IncomingInputs[0] - SourceOffset;
8559         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8560                      InputFixed);
8561         IncomingInputs[0] = InputFixed;
8562       }
8563     } else if (IncomingInputs.size() == 2) {
8564       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8565           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8566         // We have two non-adjacent or clobbered inputs we need to extract from
8567         // the source half. To do this, we need to map them into some adjacent
8568         // dword slot in the source mask.
8569         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8570                               IncomingInputs[1] - SourceOffset};
8571
8572         // If there is a free slot in the source half mask adjacent to one of
8573         // the inputs, place the other input in it. We use (Index XOR 1) to
8574         // compute an adjacent index.
8575         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8576             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8577           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8578           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8579           InputsFixed[1] = InputsFixed[0] ^ 1;
8580         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8581                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8582           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8583           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8584           InputsFixed[0] = InputsFixed[1] ^ 1;
8585         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8586                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8587           // The two inputs are in the same DWord but it is clobbered and the
8588           // adjacent DWord isn't used at all. Move both inputs to the free
8589           // slot.
8590           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8591           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8592           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8593           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8594         } else {
8595           // The only way we hit this point is if there is no clobbering
8596           // (because there are no off-half inputs to this half) and there is no
8597           // free slot adjacent to one of the inputs. In this case, we have to
8598           // swap an input with a non-input.
8599           for (int i = 0; i < 4; ++i)
8600             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8601                    "We can't handle any clobbers here!");
8602           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8603                  "Cannot have adjacent inputs here!");
8604
8605           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8606           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8607
8608           // We also have to update the final source mask in this case because
8609           // it may need to undo the above swap.
8610           for (int &M : FinalSourceHalfMask)
8611             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8612               M = InputsFixed[1] + SourceOffset;
8613             else if (M == InputsFixed[1] + SourceOffset)
8614               M = (InputsFixed[0] ^ 1) + SourceOffset;
8615
8616           InputsFixed[1] = InputsFixed[0] ^ 1;
8617         }
8618
8619         // Point everything at the fixed inputs.
8620         for (int &M : HalfMask)
8621           if (M == IncomingInputs[0])
8622             M = InputsFixed[0] + SourceOffset;
8623           else if (M == IncomingInputs[1])
8624             M = InputsFixed[1] + SourceOffset;
8625
8626         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8627         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8628       }
8629     } else {
8630       llvm_unreachable("Unhandled input size!");
8631     }
8632
8633     // Now hoist the DWord down to the right half.
8634     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8635     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8636     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8637     for (int &M : HalfMask)
8638       for (int Input : IncomingInputs)
8639         if (M == Input)
8640           M = FreeDWord * 2 + Input % 2;
8641   };
8642   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8643                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8644   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8645                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8646
8647   // Now enact all the shuffles we've computed to move the inputs into their
8648   // target half.
8649   if (!isNoopShuffleMask(PSHUFLMask))
8650     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8651                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8652   if (!isNoopShuffleMask(PSHUFHMask))
8653     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8654                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8655   if (!isNoopShuffleMask(PSHUFDMask))
8656     V = DAG.getBitcast(
8657         VT,
8658         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8659                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8660
8661   // At this point, each half should contain all its inputs, and we can then
8662   // just shuffle them into their final position.
8663   assert(std::count_if(LoMask.begin(), LoMask.end(),
8664                        [](int M) { return M >= 4; }) == 0 &&
8665          "Failed to lift all the high half inputs to the low mask!");
8666   assert(std::count_if(HiMask.begin(), HiMask.end(),
8667                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8668          "Failed to lift all the low half inputs to the high mask!");
8669
8670   // Do a half shuffle for the low mask.
8671   if (!isNoopShuffleMask(LoMask))
8672     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8673                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8674
8675   // Do a half shuffle with the high mask after shifting its values down.
8676   for (int &M : HiMask)
8677     if (M >= 0)
8678       M -= 4;
8679   if (!isNoopShuffleMask(HiMask))
8680     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8681                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8682
8683   return V;
8684 }
8685
8686 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8687 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8688                                           SDValue V2, ArrayRef<int> Mask,
8689                                           SelectionDAG &DAG, bool &V1InUse,
8690                                           bool &V2InUse) {
8691   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8692   SDValue V1Mask[16];
8693   SDValue V2Mask[16];
8694   V1InUse = false;
8695   V2InUse = false;
8696
8697   int Size = Mask.size();
8698   int Scale = 16 / Size;
8699   for (int i = 0; i < 16; ++i) {
8700     if (Mask[i / Scale] == -1) {
8701       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8702     } else {
8703       const int ZeroMask = 0x80;
8704       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8705                                           : ZeroMask;
8706       int V2Idx = Mask[i / Scale] < Size
8707                       ? ZeroMask
8708                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8709       if (Zeroable[i / Scale])
8710         V1Idx = V2Idx = ZeroMask;
8711       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8712       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8713       V1InUse |= (ZeroMask != V1Idx);
8714       V2InUse |= (ZeroMask != V2Idx);
8715     }
8716   }
8717
8718   if (V1InUse)
8719     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8720                      DAG.getBitcast(MVT::v16i8, V1),
8721                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8722   if (V2InUse)
8723     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8724                      DAG.getBitcast(MVT::v16i8, V2),
8725                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8726
8727   // If we need shuffled inputs from both, blend the two.
8728   SDValue V;
8729   if (V1InUse && V2InUse)
8730     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8731   else
8732     V = V1InUse ? V1 : V2;
8733
8734   // Cast the result back to the correct type.
8735   return DAG.getBitcast(VT, V);
8736 }
8737
8738 /// \brief Generic lowering of 8-lane i16 shuffles.
8739 ///
8740 /// This handles both single-input shuffles and combined shuffle/blends with
8741 /// two inputs. The single input shuffles are immediately delegated to
8742 /// a dedicated lowering routine.
8743 ///
8744 /// The blends are lowered in one of three fundamental ways. If there are few
8745 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8746 /// of the input is significantly cheaper when lowered as an interleaving of
8747 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8748 /// halves of the inputs separately (making them have relatively few inputs)
8749 /// and then concatenate them.
8750 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8751                                        const X86Subtarget *Subtarget,
8752                                        SelectionDAG &DAG) {
8753   SDLoc DL(Op);
8754   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8755   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8756   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8757   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8758   ArrayRef<int> OrigMask = SVOp->getMask();
8759   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8760                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8761   MutableArrayRef<int> Mask(MaskStorage);
8762
8763   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8764
8765   // Whenever we can lower this as a zext, that instruction is strictly faster
8766   // than any alternative.
8767   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8768           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8769     return ZExt;
8770
8771   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8772   (void)isV1;
8773   auto isV2 = [](int M) { return M >= 8; };
8774
8775   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8776
8777   if (NumV2Inputs == 0) {
8778     // Check for being able to broadcast a single element.
8779     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8780                                                           Mask, Subtarget, DAG))
8781       return Broadcast;
8782
8783     // Try to use shift instructions.
8784     if (SDValue Shift =
8785             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8786       return Shift;
8787
8788     // Use dedicated unpack instructions for masks that match their pattern.
8789     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8790       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8791     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8792       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8793
8794     // Try to use byte rotation instructions.
8795     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8796                                                         Mask, Subtarget, DAG))
8797       return Rotate;
8798
8799     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8800                                                      Subtarget, DAG);
8801   }
8802
8803   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8804          "All single-input shuffles should be canonicalized to be V1-input "
8805          "shuffles.");
8806
8807   // Try to use shift instructions.
8808   if (SDValue Shift =
8809           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8810     return Shift;
8811
8812   // See if we can use SSE4A Extraction / Insertion.
8813   if (Subtarget->hasSSE4A())
8814     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8815       return V;
8816
8817   // There are special ways we can lower some single-element blends.
8818   if (NumV2Inputs == 1)
8819     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8820                                                          Mask, Subtarget, DAG))
8821       return V;
8822
8823   // We have different paths for blend lowering, but they all must use the
8824   // *exact* same predicate.
8825   bool IsBlendSupported = Subtarget->hasSSE41();
8826   if (IsBlendSupported)
8827     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8828                                                   Subtarget, DAG))
8829       return Blend;
8830
8831   if (SDValue Masked =
8832           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8833     return Masked;
8834
8835   // Use dedicated unpack instructions for masks that match their pattern.
8836   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8837     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8838   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8839     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8840
8841   // Try to use byte rotation instructions.
8842   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8843           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8844     return Rotate;
8845
8846   if (SDValue BitBlend =
8847           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8848     return BitBlend;
8849
8850   if (SDValue Unpack =
8851           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8852     return Unpack;
8853
8854   // If we can't directly blend but can use PSHUFB, that will be better as it
8855   // can both shuffle and set up the inefficient blend.
8856   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8857     bool V1InUse, V2InUse;
8858     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8859                                       V1InUse, V2InUse);
8860   }
8861
8862   // We can always bit-blend if we have to so the fallback strategy is to
8863   // decompose into single-input permutes and blends.
8864   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8865                                                       Mask, DAG);
8866 }
8867
8868 /// \brief Check whether a compaction lowering can be done by dropping even
8869 /// elements and compute how many times even elements must be dropped.
8870 ///
8871 /// This handles shuffles which take every Nth element where N is a power of
8872 /// two. Example shuffle masks:
8873 ///
8874 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8875 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8876 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8877 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8878 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8879 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8880 ///
8881 /// Any of these lanes can of course be undef.
8882 ///
8883 /// This routine only supports N <= 3.
8884 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8885 /// for larger N.
8886 ///
8887 /// \returns N above, or the number of times even elements must be dropped if
8888 /// there is such a number. Otherwise returns zero.
8889 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8890   // Figure out whether we're looping over two inputs or just one.
8891   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8892
8893   // The modulus for the shuffle vector entries is based on whether this is
8894   // a single input or not.
8895   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8896   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8897          "We should only be called with masks with a power-of-2 size!");
8898
8899   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8900
8901   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8902   // and 2^3 simultaneously. This is because we may have ambiguity with
8903   // partially undef inputs.
8904   bool ViableForN[3] = {true, true, true};
8905
8906   for (int i = 0, e = Mask.size(); i < e; ++i) {
8907     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8908     // want.
8909     if (Mask[i] == -1)
8910       continue;
8911
8912     bool IsAnyViable = false;
8913     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8914       if (ViableForN[j]) {
8915         uint64_t N = j + 1;
8916
8917         // The shuffle mask must be equal to (i * 2^N) % M.
8918         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8919           IsAnyViable = true;
8920         else
8921           ViableForN[j] = false;
8922       }
8923     // Early exit if we exhaust the possible powers of two.
8924     if (!IsAnyViable)
8925       break;
8926   }
8927
8928   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8929     if (ViableForN[j])
8930       return j + 1;
8931
8932   // Return 0 as there is no viable power of two.
8933   return 0;
8934 }
8935
8936 /// \brief Generic lowering of v16i8 shuffles.
8937 ///
8938 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8939 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8940 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8941 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8942 /// back together.
8943 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8944                                        const X86Subtarget *Subtarget,
8945                                        SelectionDAG &DAG) {
8946   SDLoc DL(Op);
8947   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8948   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8949   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8950   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8951   ArrayRef<int> Mask = SVOp->getMask();
8952   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8953
8954   // Try to use shift instructions.
8955   if (SDValue Shift =
8956           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8957     return Shift;
8958
8959   // Try to use byte rotation instructions.
8960   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8961           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8962     return Rotate;
8963
8964   // Try to use a zext lowering.
8965   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8966           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8967     return ZExt;
8968
8969   // See if we can use SSE4A Extraction / Insertion.
8970   if (Subtarget->hasSSE4A())
8971     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8972       return V;
8973
8974   int NumV2Elements =
8975       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8976
8977   // For single-input shuffles, there are some nicer lowering tricks we can use.
8978   if (NumV2Elements == 0) {
8979     // Check for being able to broadcast a single element.
8980     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8981                                                           Mask, Subtarget, DAG))
8982       return Broadcast;
8983
8984     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8985     // Notably, this handles splat and partial-splat shuffles more efficiently.
8986     // However, it only makes sense if the pre-duplication shuffle simplifies
8987     // things significantly. Currently, this means we need to be able to
8988     // express the pre-duplication shuffle as an i16 shuffle.
8989     //
8990     // FIXME: We should check for other patterns which can be widened into an
8991     // i16 shuffle as well.
8992     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8993       for (int i = 0; i < 16; i += 2)
8994         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8995           return false;
8996
8997       return true;
8998     };
8999     auto tryToWidenViaDuplication = [&]() -> SDValue {
9000       if (!canWidenViaDuplication(Mask))
9001         return SDValue();
9002       SmallVector<int, 4> LoInputs;
9003       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9004                    [](int M) { return M >= 0 && M < 8; });
9005       std::sort(LoInputs.begin(), LoInputs.end());
9006       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9007                      LoInputs.end());
9008       SmallVector<int, 4> HiInputs;
9009       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9010                    [](int M) { return M >= 8; });
9011       std::sort(HiInputs.begin(), HiInputs.end());
9012       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9013                      HiInputs.end());
9014
9015       bool TargetLo = LoInputs.size() >= HiInputs.size();
9016       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9017       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9018
9019       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9020       SmallDenseMap<int, int, 8> LaneMap;
9021       for (int I : InPlaceInputs) {
9022         PreDupI16Shuffle[I/2] = I/2;
9023         LaneMap[I] = I;
9024       }
9025       int j = TargetLo ? 0 : 4, je = j + 4;
9026       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9027         // Check if j is already a shuffle of this input. This happens when
9028         // there are two adjacent bytes after we move the low one.
9029         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9030           // If we haven't yet mapped the input, search for a slot into which
9031           // we can map it.
9032           while (j < je && PreDupI16Shuffle[j] != -1)
9033             ++j;
9034
9035           if (j == je)
9036             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9037             return SDValue();
9038
9039           // Map this input with the i16 shuffle.
9040           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9041         }
9042
9043         // Update the lane map based on the mapping we ended up with.
9044         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9045       }
9046       V1 = DAG.getBitcast(
9047           MVT::v16i8,
9048           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9049                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9050
9051       // Unpack the bytes to form the i16s that will be shuffled into place.
9052       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9053                        MVT::v16i8, V1, V1);
9054
9055       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9056       for (int i = 0; i < 16; ++i)
9057         if (Mask[i] != -1) {
9058           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9059           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9060           if (PostDupI16Shuffle[i / 2] == -1)
9061             PostDupI16Shuffle[i / 2] = MappedMask;
9062           else
9063             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9064                    "Conflicting entrties in the original shuffle!");
9065         }
9066       return DAG.getBitcast(
9067           MVT::v16i8,
9068           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9069                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9070     };
9071     if (SDValue V = tryToWidenViaDuplication())
9072       return V;
9073   }
9074
9075   if (SDValue Masked =
9076           lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9077     return Masked;
9078
9079   // Use dedicated unpack instructions for masks that match their pattern.
9080   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9081                                          0, 16, 1, 17, 2, 18, 3, 19,
9082                                          // High half.
9083                                          4, 20, 5, 21, 6, 22, 7, 23}))
9084     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9085   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9086                                          8, 24, 9, 25, 10, 26, 11, 27,
9087                                          // High half.
9088                                          12, 28, 13, 29, 14, 30, 15, 31}))
9089     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9090
9091   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9092   // with PSHUFB. It is important to do this before we attempt to generate any
9093   // blends but after all of the single-input lowerings. If the single input
9094   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9095   // want to preserve that and we can DAG combine any longer sequences into
9096   // a PSHUFB in the end. But once we start blending from multiple inputs,
9097   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9098   // and there are *very* few patterns that would actually be faster than the
9099   // PSHUFB approach because of its ability to zero lanes.
9100   //
9101   // FIXME: The only exceptions to the above are blends which are exact
9102   // interleavings with direct instructions supporting them. We currently don't
9103   // handle those well here.
9104   if (Subtarget->hasSSSE3()) {
9105     bool V1InUse = false;
9106     bool V2InUse = false;
9107
9108     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9109                                                 DAG, V1InUse, V2InUse);
9110
9111     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9112     // do so. This avoids using them to handle blends-with-zero which is
9113     // important as a single pshufb is significantly faster for that.
9114     if (V1InUse && V2InUse) {
9115       if (Subtarget->hasSSE41())
9116         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9117                                                       Mask, Subtarget, DAG))
9118           return Blend;
9119
9120       // We can use an unpack to do the blending rather than an or in some
9121       // cases. Even though the or may be (very minorly) more efficient, we
9122       // preference this lowering because there are common cases where part of
9123       // the complexity of the shuffles goes away when we do the final blend as
9124       // an unpack.
9125       // FIXME: It might be worth trying to detect if the unpack-feeding
9126       // shuffles will both be pshufb, in which case we shouldn't bother with
9127       // this.
9128       if (SDValue Unpack =
9129               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9130         return Unpack;
9131     }
9132
9133     return PSHUFB;
9134   }
9135
9136   // There are special ways we can lower some single-element blends.
9137   if (NumV2Elements == 1)
9138     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9139                                                          Mask, Subtarget, DAG))
9140       return V;
9141
9142   if (SDValue BitBlend =
9143           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9144     return BitBlend;
9145
9146   // Check whether a compaction lowering can be done. This handles shuffles
9147   // which take every Nth element for some even N. See the helper function for
9148   // details.
9149   //
9150   // We special case these as they can be particularly efficiently handled with
9151   // the PACKUSB instruction on x86 and they show up in common patterns of
9152   // rearranging bytes to truncate wide elements.
9153   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9154     // NumEvenDrops is the power of two stride of the elements. Another way of
9155     // thinking about it is that we need to drop the even elements this many
9156     // times to get the original input.
9157     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9158
9159     // First we need to zero all the dropped bytes.
9160     assert(NumEvenDrops <= 3 &&
9161            "No support for dropping even elements more than 3 times.");
9162     // We use the mask type to pick which bytes are preserved based on how many
9163     // elements are dropped.
9164     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9165     SDValue ByteClearMask = DAG.getBitcast(
9166         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9167     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9168     if (!IsSingleInput)
9169       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9170
9171     // Now pack things back together.
9172     V1 = DAG.getBitcast(MVT::v8i16, V1);
9173     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9174     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9175     for (int i = 1; i < NumEvenDrops; ++i) {
9176       Result = DAG.getBitcast(MVT::v8i16, Result);
9177       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9178     }
9179
9180     return Result;
9181   }
9182
9183   // Handle multi-input cases by blending single-input shuffles.
9184   if (NumV2Elements > 0)
9185     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9186                                                       Mask, DAG);
9187
9188   // The fallback path for single-input shuffles widens this into two v8i16
9189   // vectors with unpacks, shuffles those, and then pulls them back together
9190   // with a pack.
9191   SDValue V = V1;
9192
9193   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9194   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9195   for (int i = 0; i < 16; ++i)
9196     if (Mask[i] >= 0)
9197       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9198
9199   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9200
9201   SDValue VLoHalf, VHiHalf;
9202   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9203   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9204   // i16s.
9205   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9206                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9207       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9208                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9209     // Use a mask to drop the high bytes.
9210     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9211     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9212                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9213
9214     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9215     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9216
9217     // Squash the masks to point directly into VLoHalf.
9218     for (int &M : LoBlendMask)
9219       if (M >= 0)
9220         M /= 2;
9221     for (int &M : HiBlendMask)
9222       if (M >= 0)
9223         M /= 2;
9224   } else {
9225     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9226     // VHiHalf so that we can blend them as i16s.
9227     VLoHalf = DAG.getBitcast(
9228         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9229     VHiHalf = DAG.getBitcast(
9230         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9231   }
9232
9233   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9234   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9235
9236   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9237 }
9238
9239 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9240 ///
9241 /// This routine breaks down the specific type of 128-bit shuffle and
9242 /// dispatches to the lowering routines accordingly.
9243 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9244                                         MVT VT, const X86Subtarget *Subtarget,
9245                                         SelectionDAG &DAG) {
9246   switch (VT.SimpleTy) {
9247   case MVT::v2i64:
9248     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9249   case MVT::v2f64:
9250     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9251   case MVT::v4i32:
9252     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9253   case MVT::v4f32:
9254     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9255   case MVT::v8i16:
9256     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9257   case MVT::v16i8:
9258     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9259
9260   default:
9261     llvm_unreachable("Unimplemented!");
9262   }
9263 }
9264
9265 /// \brief Helper function to test whether a shuffle mask could be
9266 /// simplified by widening the elements being shuffled.
9267 ///
9268 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9269 /// leaves it in an unspecified state.
9270 ///
9271 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9272 /// shuffle masks. The latter have the special property of a '-2' representing
9273 /// a zero-ed lane of a vector.
9274 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9275                                     SmallVectorImpl<int> &WidenedMask) {
9276   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9277     // If both elements are undef, its trivial.
9278     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9279       WidenedMask.push_back(SM_SentinelUndef);
9280       continue;
9281     }
9282
9283     // Check for an undef mask and a mask value properly aligned to fit with
9284     // a pair of values. If we find such a case, use the non-undef mask's value.
9285     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9286       WidenedMask.push_back(Mask[i + 1] / 2);
9287       continue;
9288     }
9289     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9290       WidenedMask.push_back(Mask[i] / 2);
9291       continue;
9292     }
9293
9294     // When zeroing, we need to spread the zeroing across both lanes to widen.
9295     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9296       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9297           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9298         WidenedMask.push_back(SM_SentinelZero);
9299         continue;
9300       }
9301       return false;
9302     }
9303
9304     // Finally check if the two mask values are adjacent and aligned with
9305     // a pair.
9306     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9307       WidenedMask.push_back(Mask[i] / 2);
9308       continue;
9309     }
9310
9311     // Otherwise we can't safely widen the elements used in this shuffle.
9312     return false;
9313   }
9314   assert(WidenedMask.size() == Mask.size() / 2 &&
9315          "Incorrect size of mask after widening the elements!");
9316
9317   return true;
9318 }
9319
9320 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9321 ///
9322 /// This routine just extracts two subvectors, shuffles them independently, and
9323 /// then concatenates them back together. This should work effectively with all
9324 /// AVX vector shuffle types.
9325 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9326                                           SDValue V2, ArrayRef<int> Mask,
9327                                           SelectionDAG &DAG) {
9328   assert(VT.getSizeInBits() >= 256 &&
9329          "Only for 256-bit or wider vector shuffles!");
9330   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9331   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9332
9333   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9334   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9335
9336   int NumElements = VT.getVectorNumElements();
9337   int SplitNumElements = NumElements / 2;
9338   MVT ScalarVT = VT.getScalarType();
9339   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9340
9341   // Rather than splitting build-vectors, just build two narrower build
9342   // vectors. This helps shuffling with splats and zeros.
9343   auto SplitVector = [&](SDValue V) {
9344     while (V.getOpcode() == ISD::BITCAST)
9345       V = V->getOperand(0);
9346
9347     MVT OrigVT = V.getSimpleValueType();
9348     int OrigNumElements = OrigVT.getVectorNumElements();
9349     int OrigSplitNumElements = OrigNumElements / 2;
9350     MVT OrigScalarVT = OrigVT.getScalarType();
9351     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9352
9353     SDValue LoV, HiV;
9354
9355     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9356     if (!BV) {
9357       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9358                         DAG.getIntPtrConstant(0, DL));
9359       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9360                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9361     } else {
9362
9363       SmallVector<SDValue, 16> LoOps, HiOps;
9364       for (int i = 0; i < OrigSplitNumElements; ++i) {
9365         LoOps.push_back(BV->getOperand(i));
9366         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9367       }
9368       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9369       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9370     }
9371     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9372                           DAG.getBitcast(SplitVT, HiV));
9373   };
9374
9375   SDValue LoV1, HiV1, LoV2, HiV2;
9376   std::tie(LoV1, HiV1) = SplitVector(V1);
9377   std::tie(LoV2, HiV2) = SplitVector(V2);
9378
9379   // Now create two 4-way blends of these half-width vectors.
9380   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9381     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9382     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9383     for (int i = 0; i < SplitNumElements; ++i) {
9384       int M = HalfMask[i];
9385       if (M >= NumElements) {
9386         if (M >= NumElements + SplitNumElements)
9387           UseHiV2 = true;
9388         else
9389           UseLoV2 = true;
9390         V2BlendMask.push_back(M - NumElements);
9391         V1BlendMask.push_back(-1);
9392         BlendMask.push_back(SplitNumElements + i);
9393       } else if (M >= 0) {
9394         if (M >= SplitNumElements)
9395           UseHiV1 = true;
9396         else
9397           UseLoV1 = true;
9398         V2BlendMask.push_back(-1);
9399         V1BlendMask.push_back(M);
9400         BlendMask.push_back(i);
9401       } else {
9402         V2BlendMask.push_back(-1);
9403         V1BlendMask.push_back(-1);
9404         BlendMask.push_back(-1);
9405       }
9406     }
9407
9408     // Because the lowering happens after all combining takes place, we need to
9409     // manually combine these blend masks as much as possible so that we create
9410     // a minimal number of high-level vector shuffle nodes.
9411
9412     // First try just blending the halves of V1 or V2.
9413     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9414       return DAG.getUNDEF(SplitVT);
9415     if (!UseLoV2 && !UseHiV2)
9416       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9417     if (!UseLoV1 && !UseHiV1)
9418       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9419
9420     SDValue V1Blend, V2Blend;
9421     if (UseLoV1 && UseHiV1) {
9422       V1Blend =
9423         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9424     } else {
9425       // We only use half of V1 so map the usage down into the final blend mask.
9426       V1Blend = UseLoV1 ? LoV1 : HiV1;
9427       for (int i = 0; i < SplitNumElements; ++i)
9428         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9429           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9430     }
9431     if (UseLoV2 && UseHiV2) {
9432       V2Blend =
9433         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9434     } else {
9435       // We only use half of V2 so map the usage down into the final blend mask.
9436       V2Blend = UseLoV2 ? LoV2 : HiV2;
9437       for (int i = 0; i < SplitNumElements; ++i)
9438         if (BlendMask[i] >= SplitNumElements)
9439           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9440     }
9441     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9442   };
9443   SDValue Lo = HalfBlend(LoMask);
9444   SDValue Hi = HalfBlend(HiMask);
9445   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9446 }
9447
9448 /// \brief Either split a vector in halves or decompose the shuffles and the
9449 /// blend.
9450 ///
9451 /// This is provided as a good fallback for many lowerings of non-single-input
9452 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9453 /// between splitting the shuffle into 128-bit components and stitching those
9454 /// back together vs. extracting the single-input shuffles and blending those
9455 /// results.
9456 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9457                                                 SDValue V2, ArrayRef<int> Mask,
9458                                                 SelectionDAG &DAG) {
9459   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9460                                             "lower single-input shuffles as it "
9461                                             "could then recurse on itself.");
9462   int Size = Mask.size();
9463
9464   // If this can be modeled as a broadcast of two elements followed by a blend,
9465   // prefer that lowering. This is especially important because broadcasts can
9466   // often fold with memory operands.
9467   auto DoBothBroadcast = [&] {
9468     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9469     for (int M : Mask)
9470       if (M >= Size) {
9471         if (V2BroadcastIdx == -1)
9472           V2BroadcastIdx = M - Size;
9473         else if (M - Size != V2BroadcastIdx)
9474           return false;
9475       } else if (M >= 0) {
9476         if (V1BroadcastIdx == -1)
9477           V1BroadcastIdx = M;
9478         else if (M != V1BroadcastIdx)
9479           return false;
9480       }
9481     return true;
9482   };
9483   if (DoBothBroadcast())
9484     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9485                                                       DAG);
9486
9487   // If the inputs all stem from a single 128-bit lane of each input, then we
9488   // split them rather than blending because the split will decompose to
9489   // unusually few instructions.
9490   int LaneCount = VT.getSizeInBits() / 128;
9491   int LaneSize = Size / LaneCount;
9492   SmallBitVector LaneInputs[2];
9493   LaneInputs[0].resize(LaneCount, false);
9494   LaneInputs[1].resize(LaneCount, false);
9495   for (int i = 0; i < Size; ++i)
9496     if (Mask[i] >= 0)
9497       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9498   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9499     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9500
9501   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9502   // that the decomposed single-input shuffles don't end up here.
9503   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9504 }
9505
9506 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9507 /// a permutation and blend of those lanes.
9508 ///
9509 /// This essentially blends the out-of-lane inputs to each lane into the lane
9510 /// from a permuted copy of the vector. This lowering strategy results in four
9511 /// instructions in the worst case for a single-input cross lane shuffle which
9512 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9513 /// of. Special cases for each particular shuffle pattern should be handled
9514 /// prior to trying this lowering.
9515 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9516                                                        SDValue V1, SDValue V2,
9517                                                        ArrayRef<int> Mask,
9518                                                        SelectionDAG &DAG) {
9519   // FIXME: This should probably be generalized for 512-bit vectors as well.
9520   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9521   int LaneSize = Mask.size() / 2;
9522
9523   // If there are only inputs from one 128-bit lane, splitting will in fact be
9524   // less expensive. The flags track whether the given lane contains an element
9525   // that crosses to another lane.
9526   bool LaneCrossing[2] = {false, false};
9527   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9528     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9529       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9530   if (!LaneCrossing[0] || !LaneCrossing[1])
9531     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9532
9533   if (isSingleInputShuffleMask(Mask)) {
9534     SmallVector<int, 32> FlippedBlendMask;
9535     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9536       FlippedBlendMask.push_back(
9537           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9538                                   ? Mask[i]
9539                                   : Mask[i] % LaneSize +
9540                                         (i / LaneSize) * LaneSize + Size));
9541
9542     // Flip the vector, and blend the results which should now be in-lane. The
9543     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9544     // 5 for the high source. The value 3 selects the high half of source 2 and
9545     // the value 2 selects the low half of source 2. We only use source 2 to
9546     // allow folding it into a memory operand.
9547     unsigned PERMMask = 3 | 2 << 4;
9548     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9549                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9550     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9551   }
9552
9553   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9554   // will be handled by the above logic and a blend of the results, much like
9555   // other patterns in AVX.
9556   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9557 }
9558
9559 /// \brief Handle lowering 2-lane 128-bit shuffles.
9560 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9561                                         SDValue V2, ArrayRef<int> Mask,
9562                                         const X86Subtarget *Subtarget,
9563                                         SelectionDAG &DAG) {
9564   // TODO: If minimizing size and one of the inputs is a zero vector and the
9565   // the zero vector has only one use, we could use a VPERM2X128 to save the
9566   // instruction bytes needed to explicitly generate the zero vector.
9567
9568   // Blends are faster and handle all the non-lane-crossing cases.
9569   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9570                                                 Subtarget, DAG))
9571     return Blend;
9572
9573   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9574   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9575
9576   // If either input operand is a zero vector, use VPERM2X128 because its mask
9577   // allows us to replace the zero input with an implicit zero.
9578   if (!IsV1Zero && !IsV2Zero) {
9579     // Check for patterns which can be matched with a single insert of a 128-bit
9580     // subvector.
9581     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9582     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9583       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9584                                    VT.getVectorNumElements() / 2);
9585       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9586                                 DAG.getIntPtrConstant(0, DL));
9587       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9588                                 OnlyUsesV1 ? V1 : V2,
9589                                 DAG.getIntPtrConstant(0, DL));
9590       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9591     }
9592   }
9593
9594   // Otherwise form a 128-bit permutation. After accounting for undefs,
9595   // convert the 64-bit shuffle mask selection values into 128-bit
9596   // selection bits by dividing the indexes by 2 and shifting into positions
9597   // defined by a vperm2*128 instruction's immediate control byte.
9598
9599   // The immediate permute control byte looks like this:
9600   //    [1:0] - select 128 bits from sources for low half of destination
9601   //    [2]   - ignore
9602   //    [3]   - zero low half of destination
9603   //    [5:4] - select 128 bits from sources for high half of destination
9604   //    [6]   - ignore
9605   //    [7]   - zero high half of destination
9606
9607   int MaskLO = Mask[0];
9608   if (MaskLO == SM_SentinelUndef)
9609     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9610
9611   int MaskHI = Mask[2];
9612   if (MaskHI == SM_SentinelUndef)
9613     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9614
9615   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9616
9617   // If either input is a zero vector, replace it with an undef input.
9618   // Shuffle mask values <  4 are selecting elements of V1.
9619   // Shuffle mask values >= 4 are selecting elements of V2.
9620   // Adjust each half of the permute mask by clearing the half that was
9621   // selecting the zero vector and setting the zero mask bit.
9622   if (IsV1Zero) {
9623     V1 = DAG.getUNDEF(VT);
9624     if (MaskLO < 4)
9625       PermMask = (PermMask & 0xf0) | 0x08;
9626     if (MaskHI < 4)
9627       PermMask = (PermMask & 0x0f) | 0x80;
9628   }
9629   if (IsV2Zero) {
9630     V2 = DAG.getUNDEF(VT);
9631     if (MaskLO >= 4)
9632       PermMask = (PermMask & 0xf0) | 0x08;
9633     if (MaskHI >= 4)
9634       PermMask = (PermMask & 0x0f) | 0x80;
9635   }
9636
9637   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9638                      DAG.getConstant(PermMask, DL, MVT::i8));
9639 }
9640
9641 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9642 /// shuffling each lane.
9643 ///
9644 /// This will only succeed when the result of fixing the 128-bit lanes results
9645 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9646 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9647 /// the lane crosses early and then use simpler shuffles within each lane.
9648 ///
9649 /// FIXME: It might be worthwhile at some point to support this without
9650 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9651 /// in x86 only floating point has interesting non-repeating shuffles, and even
9652 /// those are still *marginally* more expensive.
9653 static SDValue lowerVectorShuffleByMerging128BitLanes(
9654     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9655     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9656   assert(!isSingleInputShuffleMask(Mask) &&
9657          "This is only useful with multiple inputs.");
9658
9659   int Size = Mask.size();
9660   int LaneSize = 128 / VT.getScalarSizeInBits();
9661   int NumLanes = Size / LaneSize;
9662   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9663
9664   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9665   // check whether the in-128-bit lane shuffles share a repeating pattern.
9666   SmallVector<int, 4> Lanes;
9667   Lanes.resize(NumLanes, -1);
9668   SmallVector<int, 4> InLaneMask;
9669   InLaneMask.resize(LaneSize, -1);
9670   for (int i = 0; i < Size; ++i) {
9671     if (Mask[i] < 0)
9672       continue;
9673
9674     int j = i / LaneSize;
9675
9676     if (Lanes[j] < 0) {
9677       // First entry we've seen for this lane.
9678       Lanes[j] = Mask[i] / LaneSize;
9679     } else if (Lanes[j] != Mask[i] / LaneSize) {
9680       // This doesn't match the lane selected previously!
9681       return SDValue();
9682     }
9683
9684     // Check that within each lane we have a consistent shuffle mask.
9685     int k = i % LaneSize;
9686     if (InLaneMask[k] < 0) {
9687       InLaneMask[k] = Mask[i] % LaneSize;
9688     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9689       // This doesn't fit a repeating in-lane mask.
9690       return SDValue();
9691     }
9692   }
9693
9694   // First shuffle the lanes into place.
9695   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9696                                 VT.getSizeInBits() / 64);
9697   SmallVector<int, 8> LaneMask;
9698   LaneMask.resize(NumLanes * 2, -1);
9699   for (int i = 0; i < NumLanes; ++i)
9700     if (Lanes[i] >= 0) {
9701       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9702       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9703     }
9704
9705   V1 = DAG.getBitcast(LaneVT, V1);
9706   V2 = DAG.getBitcast(LaneVT, V2);
9707   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9708
9709   // Cast it back to the type we actually want.
9710   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9711
9712   // Now do a simple shuffle that isn't lane crossing.
9713   SmallVector<int, 8> NewMask;
9714   NewMask.resize(Size, -1);
9715   for (int i = 0; i < Size; ++i)
9716     if (Mask[i] >= 0)
9717       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9718   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9719          "Must not introduce lane crosses at this point!");
9720
9721   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9722 }
9723
9724 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9725 /// given mask.
9726 ///
9727 /// This returns true if the elements from a particular input are already in the
9728 /// slot required by the given mask and require no permutation.
9729 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9730   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9731   int Size = Mask.size();
9732   for (int i = 0; i < Size; ++i)
9733     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9734       return false;
9735
9736   return true;
9737 }
9738
9739 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9740                                             ArrayRef<int> Mask, SDValue V1,
9741                                             SDValue V2, SelectionDAG &DAG) {
9742
9743   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9744   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9745   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9746   int NumElts = VT.getVectorNumElements();
9747   bool ShufpdMask = true;
9748   bool CommutableMask = true;
9749   unsigned Immediate = 0;
9750   for (int i = 0; i < NumElts; ++i) {
9751     if (Mask[i] < 0)
9752       continue;
9753     int Val = (i & 6) + NumElts * (i & 1);
9754     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9755     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9756       ShufpdMask = false;
9757     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9758       CommutableMask = false;
9759     Immediate |= (Mask[i] % 2) << i;
9760   }
9761   if (ShufpdMask)
9762     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9763                        DAG.getConstant(Immediate, DL, MVT::i8));
9764   if (CommutableMask)
9765     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9766                        DAG.getConstant(Immediate, DL, MVT::i8));
9767   return SDValue();
9768 }
9769
9770 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9771 ///
9772 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9773 /// isn't available.
9774 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9775                                        const X86Subtarget *Subtarget,
9776                                        SelectionDAG &DAG) {
9777   SDLoc DL(Op);
9778   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9779   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9780   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9781   ArrayRef<int> Mask = SVOp->getMask();
9782   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9783
9784   SmallVector<int, 4> WidenedMask;
9785   if (canWidenShuffleElements(Mask, WidenedMask))
9786     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9787                                     DAG);
9788
9789   if (isSingleInputShuffleMask(Mask)) {
9790     // Check for being able to broadcast a single element.
9791     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9792                                                           Mask, Subtarget, DAG))
9793       return Broadcast;
9794
9795     // Use low duplicate instructions for masks that match their pattern.
9796     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9797       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9798
9799     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9800       // Non-half-crossing single input shuffles can be lowerid with an
9801       // interleaved permutation.
9802       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9803                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9804       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9805                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9806     }
9807
9808     // With AVX2 we have direct support for this permutation.
9809     if (Subtarget->hasAVX2())
9810       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9811                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9812
9813     // Otherwise, fall back.
9814     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9815                                                    DAG);
9816   }
9817
9818   // X86 has dedicated unpack instructions that can handle specific blend
9819   // operations: UNPCKH and UNPCKL.
9820   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9821     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9822   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9823     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9824   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9825     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9826   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9827     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9828
9829   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9830                                                 Subtarget, DAG))
9831     return Blend;
9832
9833   // Check if the blend happens to exactly fit that of SHUFPD.
9834   if (SDValue Op =
9835       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9836     return Op;
9837
9838   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9839   // shuffle. However, if we have AVX2 and either inputs are already in place,
9840   // we will be able to shuffle even across lanes the other input in a single
9841   // instruction so skip this pattern.
9842   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9843                                  isShuffleMaskInputInPlace(1, Mask))))
9844     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9845             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9846       return Result;
9847
9848   // If we have AVX2 then we always want to lower with a blend because an v4 we
9849   // can fully permute the elements.
9850   if (Subtarget->hasAVX2())
9851     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9852                                                       Mask, DAG);
9853
9854   // Otherwise fall back on generic lowering.
9855   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9856 }
9857
9858 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9859 ///
9860 /// This routine is only called when we have AVX2 and thus a reasonable
9861 /// instruction set for v4i64 shuffling..
9862 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9863                                        const X86Subtarget *Subtarget,
9864                                        SelectionDAG &DAG) {
9865   SDLoc DL(Op);
9866   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9867   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9868   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9869   ArrayRef<int> Mask = SVOp->getMask();
9870   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9871   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9872
9873   SmallVector<int, 4> WidenedMask;
9874   if (canWidenShuffleElements(Mask, WidenedMask))
9875     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9876                                     DAG);
9877
9878   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9879                                                 Subtarget, DAG))
9880     return Blend;
9881
9882   // Check for being able to broadcast a single element.
9883   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9884                                                         Mask, Subtarget, DAG))
9885     return Broadcast;
9886
9887   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9888   // use lower latency instructions that will operate on both 128-bit lanes.
9889   SmallVector<int, 2> RepeatedMask;
9890   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9891     if (isSingleInputShuffleMask(Mask)) {
9892       int PSHUFDMask[] = {-1, -1, -1, -1};
9893       for (int i = 0; i < 2; ++i)
9894         if (RepeatedMask[i] >= 0) {
9895           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9896           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9897         }
9898       return DAG.getBitcast(
9899           MVT::v4i64,
9900           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9901                       DAG.getBitcast(MVT::v8i32, V1),
9902                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9903     }
9904   }
9905
9906   // AVX2 provides a direct instruction for permuting a single input across
9907   // lanes.
9908   if (isSingleInputShuffleMask(Mask))
9909     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9910                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9911
9912   // Try to use shift instructions.
9913   if (SDValue Shift =
9914           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9915     return Shift;
9916
9917   // Use dedicated unpack instructions for masks that match their pattern.
9918   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9919     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9920   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9921     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9922   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9923     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9924   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9925     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9926
9927   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9928   // shuffle. However, if we have AVX2 and either inputs are already in place,
9929   // we will be able to shuffle even across lanes the other input in a single
9930   // instruction so skip this pattern.
9931   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9932                                  isShuffleMaskInputInPlace(1, Mask))))
9933     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9934             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9935       return Result;
9936
9937   // Otherwise fall back on generic blend lowering.
9938   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9939                                                     Mask, DAG);
9940 }
9941
9942 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9943 ///
9944 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9945 /// isn't available.
9946 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9947                                        const X86Subtarget *Subtarget,
9948                                        SelectionDAG &DAG) {
9949   SDLoc DL(Op);
9950   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9951   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9952   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9953   ArrayRef<int> Mask = SVOp->getMask();
9954   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9955
9956   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9957                                                 Subtarget, DAG))
9958     return Blend;
9959
9960   // Check for being able to broadcast a single element.
9961   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9962                                                         Mask, Subtarget, DAG))
9963     return Broadcast;
9964
9965   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9966   // options to efficiently lower the shuffle.
9967   SmallVector<int, 4> RepeatedMask;
9968   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9969     assert(RepeatedMask.size() == 4 &&
9970            "Repeated masks must be half the mask width!");
9971
9972     // Use even/odd duplicate instructions for masks that match their pattern.
9973     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9974       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9975     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9976       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9977
9978     if (isSingleInputShuffleMask(Mask))
9979       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9980                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9981
9982     // Use dedicated unpack instructions for masks that match their pattern.
9983     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9984       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9985     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9986       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9987     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9988       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9989     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9990       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9991
9992     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9993     // have already handled any direct blends. We also need to squash the
9994     // repeated mask into a simulated v4f32 mask.
9995     for (int i = 0; i < 4; ++i)
9996       if (RepeatedMask[i] >= 8)
9997         RepeatedMask[i] -= 4;
9998     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9999   }
10000
10001   // If we have a single input shuffle with different shuffle patterns in the
10002   // two 128-bit lanes use the variable mask to VPERMILPS.
10003   if (isSingleInputShuffleMask(Mask)) {
10004     SDValue VPermMask[8];
10005     for (int i = 0; i < 8; ++i)
10006       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10007                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10008     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10009       return DAG.getNode(
10010           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10011           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10012
10013     if (Subtarget->hasAVX2())
10014       return DAG.getNode(
10015           X86ISD::VPERMV, DL, MVT::v8f32,
10016           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10017                                                  MVT::v8i32, VPermMask)),
10018           V1);
10019
10020     // Otherwise, fall back.
10021     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10022                                                    DAG);
10023   }
10024
10025   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10026   // shuffle.
10027   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10028           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10029     return Result;
10030
10031   // If we have AVX2 then we always want to lower with a blend because at v8 we
10032   // can fully permute the elements.
10033   if (Subtarget->hasAVX2())
10034     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10035                                                       Mask, DAG);
10036
10037   // Otherwise fall back on generic lowering.
10038   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10039 }
10040
10041 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10042 ///
10043 /// This routine is only called when we have AVX2 and thus a reasonable
10044 /// instruction set for v8i32 shuffling..
10045 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10046                                        const X86Subtarget *Subtarget,
10047                                        SelectionDAG &DAG) {
10048   SDLoc DL(Op);
10049   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10050   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10051   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10052   ArrayRef<int> Mask = SVOp->getMask();
10053   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10054   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10055
10056   // Whenever we can lower this as a zext, that instruction is strictly faster
10057   // than any alternative. It also allows us to fold memory operands into the
10058   // shuffle in many cases.
10059   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10060                                                          Mask, Subtarget, DAG))
10061     return ZExt;
10062
10063   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10064                                                 Subtarget, DAG))
10065     return Blend;
10066
10067   // Check for being able to broadcast a single element.
10068   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10069                                                         Mask, Subtarget, DAG))
10070     return Broadcast;
10071
10072   // If the shuffle mask is repeated in each 128-bit lane we can use more
10073   // efficient instructions that mirror the shuffles across the two 128-bit
10074   // lanes.
10075   SmallVector<int, 4> RepeatedMask;
10076   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10077     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10078     if (isSingleInputShuffleMask(Mask))
10079       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10080                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10081
10082     // Use dedicated unpack instructions for masks that match their pattern.
10083     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10084       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10085     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10086       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10087     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10088       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10089     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10090       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10091   }
10092
10093   // Try to use shift instructions.
10094   if (SDValue Shift =
10095           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10096     return Shift;
10097
10098   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10099           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10100     return Rotate;
10101
10102   // If the shuffle patterns aren't repeated but it is a single input, directly
10103   // generate a cross-lane VPERMD instruction.
10104   if (isSingleInputShuffleMask(Mask)) {
10105     SDValue VPermMask[8];
10106     for (int i = 0; i < 8; ++i)
10107       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10108                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10109     return DAG.getNode(
10110         X86ISD::VPERMV, DL, MVT::v8i32,
10111         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10112   }
10113
10114   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10115   // shuffle.
10116   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10117           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10118     return Result;
10119
10120   // Otherwise fall back on generic blend lowering.
10121   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10122                                                     Mask, DAG);
10123 }
10124
10125 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10126 ///
10127 /// This routine is only called when we have AVX2 and thus a reasonable
10128 /// instruction set for v16i16 shuffling..
10129 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10130                                         const X86Subtarget *Subtarget,
10131                                         SelectionDAG &DAG) {
10132   SDLoc DL(Op);
10133   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10134   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10135   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10136   ArrayRef<int> Mask = SVOp->getMask();
10137   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10138   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10139
10140   // Whenever we can lower this as a zext, that instruction is strictly faster
10141   // than any alternative. It also allows us to fold memory operands into the
10142   // shuffle in many cases.
10143   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10144                                                          Mask, Subtarget, DAG))
10145     return ZExt;
10146
10147   // Check for being able to broadcast a single element.
10148   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10149                                                         Mask, Subtarget, DAG))
10150     return Broadcast;
10151
10152   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10153                                                 Subtarget, DAG))
10154     return Blend;
10155
10156   // Use dedicated unpack instructions for masks that match their pattern.
10157   if (isShuffleEquivalent(V1, V2, Mask,
10158                           {// First 128-bit lane:
10159                            0, 16, 1, 17, 2, 18, 3, 19,
10160                            // Second 128-bit lane:
10161                            8, 24, 9, 25, 10, 26, 11, 27}))
10162     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10163   if (isShuffleEquivalent(V1, V2, Mask,
10164                           {// First 128-bit lane:
10165                            4, 20, 5, 21, 6, 22, 7, 23,
10166                            // Second 128-bit lane:
10167                            12, 28, 13, 29, 14, 30, 15, 31}))
10168     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10169
10170   // Try to use shift instructions.
10171   if (SDValue Shift =
10172           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10173     return Shift;
10174
10175   // Try to use byte rotation instructions.
10176   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10177           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10178     return Rotate;
10179
10180   if (isSingleInputShuffleMask(Mask)) {
10181     // There are no generalized cross-lane shuffle operations available on i16
10182     // element types.
10183     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10184       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10185                                                      Mask, DAG);
10186
10187     SmallVector<int, 8> RepeatedMask;
10188     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10189       // As this is a single-input shuffle, the repeated mask should be
10190       // a strictly valid v8i16 mask that we can pass through to the v8i16
10191       // lowering to handle even the v16 case.
10192       return lowerV8I16GeneralSingleInputVectorShuffle(
10193           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10194     }
10195
10196     SDValue PSHUFBMask[32];
10197     for (int i = 0; i < 16; ++i) {
10198       if (Mask[i] == -1) {
10199         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10200         continue;
10201       }
10202
10203       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10204       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10205       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10206       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10207     }
10208     return DAG.getBitcast(MVT::v16i16,
10209                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10210                                       DAG.getBitcast(MVT::v32i8, V1),
10211                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10212                                                   MVT::v32i8, PSHUFBMask)));
10213   }
10214
10215   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10216   // shuffle.
10217   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10218           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10219     return Result;
10220
10221   // Otherwise fall back on generic lowering.
10222   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10223 }
10224
10225 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10226 ///
10227 /// This routine is only called when we have AVX2 and thus a reasonable
10228 /// instruction set for v32i8 shuffling..
10229 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10230                                        const X86Subtarget *Subtarget,
10231                                        SelectionDAG &DAG) {
10232   SDLoc DL(Op);
10233   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10234   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10235   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10236   ArrayRef<int> Mask = SVOp->getMask();
10237   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10238   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10239
10240   // Whenever we can lower this as a zext, that instruction is strictly faster
10241   // than any alternative. It also allows us to fold memory operands into the
10242   // shuffle in many cases.
10243   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10244                                                          Mask, Subtarget, DAG))
10245     return ZExt;
10246
10247   // Check for being able to broadcast a single element.
10248   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10249                                                         Mask, Subtarget, DAG))
10250     return Broadcast;
10251
10252   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10253                                                 Subtarget, DAG))
10254     return Blend;
10255
10256   // Use dedicated unpack instructions for masks that match their pattern.
10257   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10258   // 256-bit lanes.
10259   if (isShuffleEquivalent(
10260           V1, V2, Mask,
10261           {// First 128-bit lane:
10262            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10263            // Second 128-bit lane:
10264            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10265     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10266   if (isShuffleEquivalent(
10267           V1, V2, Mask,
10268           {// First 128-bit lane:
10269            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10270            // Second 128-bit lane:
10271            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10272     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10273
10274   // Try to use shift instructions.
10275   if (SDValue Shift =
10276           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10277     return Shift;
10278
10279   // Try to use byte rotation instructions.
10280   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10281           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10282     return Rotate;
10283
10284   if (isSingleInputShuffleMask(Mask)) {
10285     // There are no generalized cross-lane shuffle operations available on i8
10286     // element types.
10287     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10288       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10289                                                      Mask, DAG);
10290
10291     SDValue PSHUFBMask[32];
10292     for (int i = 0; i < 32; ++i)
10293       PSHUFBMask[i] =
10294           Mask[i] < 0
10295               ? DAG.getUNDEF(MVT::i8)
10296               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10297                                 MVT::i8);
10298
10299     return DAG.getNode(
10300         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10301         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10302   }
10303
10304   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10305   // shuffle.
10306   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10307           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10308     return Result;
10309
10310   // Otherwise fall back on generic lowering.
10311   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10312 }
10313
10314 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10315 ///
10316 /// This routine either breaks down the specific type of a 256-bit x86 vector
10317 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10318 /// together based on the available instructions.
10319 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10320                                         MVT VT, const X86Subtarget *Subtarget,
10321                                         SelectionDAG &DAG) {
10322   SDLoc DL(Op);
10323   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10324   ArrayRef<int> Mask = SVOp->getMask();
10325
10326   // If we have a single input to the zero element, insert that into V1 if we
10327   // can do so cheaply.
10328   int NumElts = VT.getVectorNumElements();
10329   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10330     return M >= NumElts;
10331   });
10332
10333   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10334     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10335                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10336       return Insertion;
10337
10338   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10339   // check for those subtargets here and avoid much of the subtarget querying in
10340   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10341   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10342   // floating point types there eventually, just immediately cast everything to
10343   // a float and operate entirely in that domain.
10344   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10345     int ElementBits = VT.getScalarSizeInBits();
10346     if (ElementBits < 32)
10347       // No floating point type available, decompose into 128-bit vectors.
10348       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10349
10350     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10351                                 VT.getVectorNumElements());
10352     V1 = DAG.getBitcast(FpVT, V1);
10353     V2 = DAG.getBitcast(FpVT, V2);
10354     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10355   }
10356
10357   switch (VT.SimpleTy) {
10358   case MVT::v4f64:
10359     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10360   case MVT::v4i64:
10361     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10362   case MVT::v8f32:
10363     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10364   case MVT::v8i32:
10365     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10366   case MVT::v16i16:
10367     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10368   case MVT::v32i8:
10369     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10370
10371   default:
10372     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10373   }
10374 }
10375
10376 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10377 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10378                                        const X86Subtarget *Subtarget,
10379                                        SelectionDAG &DAG) {
10380   SDLoc DL(Op);
10381   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10382   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10383   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10384   ArrayRef<int> Mask = SVOp->getMask();
10385   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10386
10387   // X86 has dedicated unpack instructions that can handle specific blend
10388   // operations: UNPCKH and UNPCKL.
10389   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10390     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10391   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10392     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10393
10394   // FIXME: Implement direct support for this type!
10395   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10396 }
10397
10398 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10399 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10400                                        const X86Subtarget *Subtarget,
10401                                        SelectionDAG &DAG) {
10402   SDLoc DL(Op);
10403   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10404   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10405   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10406   ArrayRef<int> Mask = SVOp->getMask();
10407   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10408
10409   // Use dedicated unpack instructions for masks that match their pattern.
10410   if (isShuffleEquivalent(V1, V2, Mask,
10411                           {// First 128-bit lane.
10412                            0, 16, 1, 17, 4, 20, 5, 21,
10413                            // Second 128-bit lane.
10414                            8, 24, 9, 25, 12, 28, 13, 29}))
10415     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10416   if (isShuffleEquivalent(V1, V2, Mask,
10417                           {// First 128-bit lane.
10418                            2, 18, 3, 19, 6, 22, 7, 23,
10419                            // Second 128-bit lane.
10420                            10, 26, 11, 27, 14, 30, 15, 31}))
10421     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10422
10423   // FIXME: Implement direct support for this type!
10424   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10425 }
10426
10427 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10428 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10429                                        const X86Subtarget *Subtarget,
10430                                        SelectionDAG &DAG) {
10431   SDLoc DL(Op);
10432   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10433   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10434   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10435   ArrayRef<int> Mask = SVOp->getMask();
10436   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10437
10438   // X86 has dedicated unpack instructions that can handle specific blend
10439   // operations: UNPCKH and UNPCKL.
10440   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10441     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10442   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10443     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10444
10445   // FIXME: Implement direct support for this type!
10446   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10447 }
10448
10449 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10450 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10451                                        const X86Subtarget *Subtarget,
10452                                        SelectionDAG &DAG) {
10453   SDLoc DL(Op);
10454   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10455   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10456   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10457   ArrayRef<int> Mask = SVOp->getMask();
10458   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10459
10460   // Use dedicated unpack instructions for masks that match their pattern.
10461   if (isShuffleEquivalent(V1, V2, Mask,
10462                           {// First 128-bit lane.
10463                            0, 16, 1, 17, 4, 20, 5, 21,
10464                            // Second 128-bit lane.
10465                            8, 24, 9, 25, 12, 28, 13, 29}))
10466     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10467   if (isShuffleEquivalent(V1, V2, Mask,
10468                           {// First 128-bit lane.
10469                            2, 18, 3, 19, 6, 22, 7, 23,
10470                            // Second 128-bit lane.
10471                            10, 26, 11, 27, 14, 30, 15, 31}))
10472     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10473
10474   // FIXME: Implement direct support for this type!
10475   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10476 }
10477
10478 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10479 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10480                                         const X86Subtarget *Subtarget,
10481                                         SelectionDAG &DAG) {
10482   SDLoc DL(Op);
10483   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10484   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10485   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10486   ArrayRef<int> Mask = SVOp->getMask();
10487   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10488   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10489
10490   // FIXME: Implement direct support for this type!
10491   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10492 }
10493
10494 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10495 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10496                                        const X86Subtarget *Subtarget,
10497                                        SelectionDAG &DAG) {
10498   SDLoc DL(Op);
10499   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10500   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10501   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10502   ArrayRef<int> Mask = SVOp->getMask();
10503   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10504   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10505
10506   // FIXME: Implement direct support for this type!
10507   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10508 }
10509
10510 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10511 ///
10512 /// This routine either breaks down the specific type of a 512-bit x86 vector
10513 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10514 /// together based on the available instructions.
10515 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10516                                         MVT VT, const X86Subtarget *Subtarget,
10517                                         SelectionDAG &DAG) {
10518   SDLoc DL(Op);
10519   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10520   ArrayRef<int> Mask = SVOp->getMask();
10521   assert(Subtarget->hasAVX512() &&
10522          "Cannot lower 512-bit vectors w/ basic ISA!");
10523
10524   // Check for being able to broadcast a single element.
10525   if (SDValue Broadcast =
10526           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10527     return Broadcast;
10528
10529   // Dispatch to each element type for lowering. If we don't have supprot for
10530   // specific element type shuffles at 512 bits, immediately split them and
10531   // lower them. Each lowering routine of a given type is allowed to assume that
10532   // the requisite ISA extensions for that element type are available.
10533   switch (VT.SimpleTy) {
10534   case MVT::v8f64:
10535     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10536   case MVT::v16f32:
10537     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10538   case MVT::v8i64:
10539     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10540   case MVT::v16i32:
10541     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10542   case MVT::v32i16:
10543     if (Subtarget->hasBWI())
10544       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10545     break;
10546   case MVT::v64i8:
10547     if (Subtarget->hasBWI())
10548       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10549     break;
10550
10551   default:
10552     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10553   }
10554
10555   // Otherwise fall back on splitting.
10556   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10557 }
10558
10559 /// \brief Top-level lowering for x86 vector shuffles.
10560 ///
10561 /// This handles decomposition, canonicalization, and lowering of all x86
10562 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10563 /// above in helper routines. The canonicalization attempts to widen shuffles
10564 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10565 /// s.t. only one of the two inputs needs to be tested, etc.
10566 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10567                                   SelectionDAG &DAG) {
10568   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10569   ArrayRef<int> Mask = SVOp->getMask();
10570   SDValue V1 = Op.getOperand(0);
10571   SDValue V2 = Op.getOperand(1);
10572   MVT VT = Op.getSimpleValueType();
10573   int NumElements = VT.getVectorNumElements();
10574   SDLoc dl(Op);
10575
10576   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10577
10578   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10579   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10580   if (V1IsUndef && V2IsUndef)
10581     return DAG.getUNDEF(VT);
10582
10583   // When we create a shuffle node we put the UNDEF node to second operand,
10584   // but in some cases the first operand may be transformed to UNDEF.
10585   // In this case we should just commute the node.
10586   if (V1IsUndef)
10587     return DAG.getCommutedVectorShuffle(*SVOp);
10588
10589   // Check for non-undef masks pointing at an undef vector and make the masks
10590   // undef as well. This makes it easier to match the shuffle based solely on
10591   // the mask.
10592   if (V2IsUndef)
10593     for (int M : Mask)
10594       if (M >= NumElements) {
10595         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10596         for (int &M : NewMask)
10597           if (M >= NumElements)
10598             M = -1;
10599         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10600       }
10601
10602   // We actually see shuffles that are entirely re-arrangements of a set of
10603   // zero inputs. This mostly happens while decomposing complex shuffles into
10604   // simple ones. Directly lower these as a buildvector of zeros.
10605   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10606   if (Zeroable.all())
10607     return getZeroVector(VT, Subtarget, DAG, dl);
10608
10609   // Try to collapse shuffles into using a vector type with fewer elements but
10610   // wider element types. We cap this to not form integers or floating point
10611   // elements wider than 64 bits, but it might be interesting to form i128
10612   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10613   SmallVector<int, 16> WidenedMask;
10614   if (VT.getScalarSizeInBits() < 64 &&
10615       canWidenShuffleElements(Mask, WidenedMask)) {
10616     MVT NewEltVT = VT.isFloatingPoint()
10617                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10618                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10619     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10620     // Make sure that the new vector type is legal. For example, v2f64 isn't
10621     // legal on SSE1.
10622     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10623       V1 = DAG.getBitcast(NewVT, V1);
10624       V2 = DAG.getBitcast(NewVT, V2);
10625       return DAG.getBitcast(
10626           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10627     }
10628   }
10629
10630   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10631   for (int M : SVOp->getMask())
10632     if (M < 0)
10633       ++NumUndefElements;
10634     else if (M < NumElements)
10635       ++NumV1Elements;
10636     else
10637       ++NumV2Elements;
10638
10639   // Commute the shuffle as needed such that more elements come from V1 than
10640   // V2. This allows us to match the shuffle pattern strictly on how many
10641   // elements come from V1 without handling the symmetric cases.
10642   if (NumV2Elements > NumV1Elements)
10643     return DAG.getCommutedVectorShuffle(*SVOp);
10644
10645   // When the number of V1 and V2 elements are the same, try to minimize the
10646   // number of uses of V2 in the low half of the vector. When that is tied,
10647   // ensure that the sum of indices for V1 is equal to or lower than the sum
10648   // indices for V2. When those are equal, try to ensure that the number of odd
10649   // indices for V1 is lower than the number of odd indices for V2.
10650   if (NumV1Elements == NumV2Elements) {
10651     int LowV1Elements = 0, LowV2Elements = 0;
10652     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10653       if (M >= NumElements)
10654         ++LowV2Elements;
10655       else if (M >= 0)
10656         ++LowV1Elements;
10657     if (LowV2Elements > LowV1Elements) {
10658       return DAG.getCommutedVectorShuffle(*SVOp);
10659     } else if (LowV2Elements == LowV1Elements) {
10660       int SumV1Indices = 0, SumV2Indices = 0;
10661       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10662         if (SVOp->getMask()[i] >= NumElements)
10663           SumV2Indices += i;
10664         else if (SVOp->getMask()[i] >= 0)
10665           SumV1Indices += i;
10666       if (SumV2Indices < SumV1Indices) {
10667         return DAG.getCommutedVectorShuffle(*SVOp);
10668       } else if (SumV2Indices == SumV1Indices) {
10669         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10670         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10671           if (SVOp->getMask()[i] >= NumElements)
10672             NumV2OddIndices += i % 2;
10673           else if (SVOp->getMask()[i] >= 0)
10674             NumV1OddIndices += i % 2;
10675         if (NumV2OddIndices < NumV1OddIndices)
10676           return DAG.getCommutedVectorShuffle(*SVOp);
10677       }
10678     }
10679   }
10680
10681   // For each vector width, delegate to a specialized lowering routine.
10682   if (VT.getSizeInBits() == 128)
10683     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10684
10685   if (VT.getSizeInBits() == 256)
10686     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10687
10688   // Force AVX-512 vectors to be scalarized for now.
10689   // FIXME: Implement AVX-512 support!
10690   if (VT.getSizeInBits() == 512)
10691     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10692
10693   llvm_unreachable("Unimplemented!");
10694 }
10695
10696 // This function assumes its argument is a BUILD_VECTOR of constants or
10697 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10698 // true.
10699 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10700                                     unsigned &MaskValue) {
10701   MaskValue = 0;
10702   unsigned NumElems = BuildVector->getNumOperands();
10703   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10704   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10705   unsigned NumElemsInLane = NumElems / NumLanes;
10706
10707   // Blend for v16i16 should be symetric for the both lanes.
10708   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10709     SDValue EltCond = BuildVector->getOperand(i);
10710     SDValue SndLaneEltCond =
10711         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10712
10713     int Lane1Cond = -1, Lane2Cond = -1;
10714     if (isa<ConstantSDNode>(EltCond))
10715       Lane1Cond = !isZero(EltCond);
10716     if (isa<ConstantSDNode>(SndLaneEltCond))
10717       Lane2Cond = !isZero(SndLaneEltCond);
10718
10719     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10720       // Lane1Cond != 0, means we want the first argument.
10721       // Lane1Cond == 0, means we want the second argument.
10722       // The encoding of this argument is 0 for the first argument, 1
10723       // for the second. Therefore, invert the condition.
10724       MaskValue |= !Lane1Cond << i;
10725     else if (Lane1Cond < 0)
10726       MaskValue |= !Lane2Cond << i;
10727     else
10728       return false;
10729   }
10730   return true;
10731 }
10732
10733 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10734 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10735                                            const X86Subtarget *Subtarget,
10736                                            SelectionDAG &DAG) {
10737   SDValue Cond = Op.getOperand(0);
10738   SDValue LHS = Op.getOperand(1);
10739   SDValue RHS = Op.getOperand(2);
10740   SDLoc dl(Op);
10741   MVT VT = Op.getSimpleValueType();
10742
10743   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10744     return SDValue();
10745   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10746
10747   // Only non-legal VSELECTs reach this lowering, convert those into generic
10748   // shuffles and re-use the shuffle lowering path for blends.
10749   SmallVector<int, 32> Mask;
10750   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10751     SDValue CondElt = CondBV->getOperand(i);
10752     Mask.push_back(
10753         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10754   }
10755   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10756 }
10757
10758 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10759   // A vselect where all conditions and data are constants can be optimized into
10760   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10761   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10762       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10763       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10764     return SDValue();
10765
10766   // Try to lower this to a blend-style vector shuffle. This can handle all
10767   // constant condition cases.
10768   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10769     return BlendOp;
10770
10771   // Variable blends are only legal from SSE4.1 onward.
10772   if (!Subtarget->hasSSE41())
10773     return SDValue();
10774
10775   // Only some types will be legal on some subtargets. If we can emit a legal
10776   // VSELECT-matching blend, return Op, and but if we need to expand, return
10777   // a null value.
10778   switch (Op.getSimpleValueType().SimpleTy) {
10779   default:
10780     // Most of the vector types have blends past SSE4.1.
10781     return Op;
10782
10783   case MVT::v32i8:
10784     // The byte blends for AVX vectors were introduced only in AVX2.
10785     if (Subtarget->hasAVX2())
10786       return Op;
10787
10788     return SDValue();
10789
10790   case MVT::v8i16:
10791   case MVT::v16i16:
10792     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10793     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10794       return Op;
10795
10796     // FIXME: We should custom lower this by fixing the condition and using i8
10797     // blends.
10798     return SDValue();
10799   }
10800 }
10801
10802 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10803   MVT VT = Op.getSimpleValueType();
10804   SDLoc dl(Op);
10805
10806   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10807     return SDValue();
10808
10809   if (VT.getSizeInBits() == 8) {
10810     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10811                                   Op.getOperand(0), Op.getOperand(1));
10812     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10813                                   DAG.getValueType(VT));
10814     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10815   }
10816
10817   if (VT.getSizeInBits() == 16) {
10818     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10819     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10820     if (Idx == 0)
10821       return DAG.getNode(
10822           ISD::TRUNCATE, dl, MVT::i16,
10823           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10824                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10825                       Op.getOperand(1)));
10826     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10827                                   Op.getOperand(0), Op.getOperand(1));
10828     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10829                                   DAG.getValueType(VT));
10830     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10831   }
10832
10833   if (VT == MVT::f32) {
10834     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10835     // the result back to FR32 register. It's only worth matching if the
10836     // result has a single use which is a store or a bitcast to i32.  And in
10837     // the case of a store, it's not worth it if the index is a constant 0,
10838     // because a MOVSSmr can be used instead, which is smaller and faster.
10839     if (!Op.hasOneUse())
10840       return SDValue();
10841     SDNode *User = *Op.getNode()->use_begin();
10842     if ((User->getOpcode() != ISD::STORE ||
10843          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10844           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10845         (User->getOpcode() != ISD::BITCAST ||
10846          User->getValueType(0) != MVT::i32))
10847       return SDValue();
10848     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10849                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10850                                   Op.getOperand(1));
10851     return DAG.getBitcast(MVT::f32, Extract);
10852   }
10853
10854   if (VT == MVT::i32 || VT == MVT::i64) {
10855     // ExtractPS/pextrq works with constant index.
10856     if (isa<ConstantSDNode>(Op.getOperand(1)))
10857       return Op;
10858   }
10859   return SDValue();
10860 }
10861
10862 /// Extract one bit from mask vector, like v16i1 or v8i1.
10863 /// AVX-512 feature.
10864 SDValue
10865 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10866   SDValue Vec = Op.getOperand(0);
10867   SDLoc dl(Vec);
10868   MVT VecVT = Vec.getSimpleValueType();
10869   SDValue Idx = Op.getOperand(1);
10870   MVT EltVT = Op.getSimpleValueType();
10871
10872   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10873   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10874          "Unexpected vector type in ExtractBitFromMaskVector");
10875
10876   // variable index can't be handled in mask registers,
10877   // extend vector to VR512
10878   if (!isa<ConstantSDNode>(Idx)) {
10879     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10880     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10881     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10882                               ExtVT.getVectorElementType(), Ext, Idx);
10883     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10884   }
10885
10886   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10887   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10888   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10889     rc = getRegClassFor(MVT::v16i1);
10890   unsigned MaxSift = rc->getSize()*8 - 1;
10891   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10892                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10893   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10894                     DAG.getConstant(MaxSift, dl, MVT::i8));
10895   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10896                        DAG.getIntPtrConstant(0, dl));
10897 }
10898
10899 SDValue
10900 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10901                                            SelectionDAG &DAG) const {
10902   SDLoc dl(Op);
10903   SDValue Vec = Op.getOperand(0);
10904   MVT VecVT = Vec.getSimpleValueType();
10905   SDValue Idx = Op.getOperand(1);
10906
10907   if (Op.getSimpleValueType() == MVT::i1)
10908     return ExtractBitFromMaskVector(Op, DAG);
10909
10910   if (!isa<ConstantSDNode>(Idx)) {
10911     if (VecVT.is512BitVector() ||
10912         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10913          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10914
10915       MVT MaskEltVT =
10916         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10917       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10918                                     MaskEltVT.getSizeInBits());
10919
10920       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10921       auto PtrVT = getPointerTy(DAG.getDataLayout());
10922       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10923                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10924                                  DAG.getConstant(0, dl, PtrVT));
10925       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10926       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10927                          DAG.getConstant(0, dl, PtrVT));
10928     }
10929     return SDValue();
10930   }
10931
10932   // If this is a 256-bit vector result, first extract the 128-bit vector and
10933   // then extract the element from the 128-bit vector.
10934   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10935
10936     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10937     // Get the 128-bit vector.
10938     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10939     MVT EltVT = VecVT.getVectorElementType();
10940
10941     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10942
10943     //if (IdxVal >= NumElems/2)
10944     //  IdxVal -= NumElems/2;
10945     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10946     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10947                        DAG.getConstant(IdxVal, dl, MVT::i32));
10948   }
10949
10950   assert(VecVT.is128BitVector() && "Unexpected vector length");
10951
10952   if (Subtarget->hasSSE41())
10953     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10954       return Res;
10955
10956   MVT VT = Op.getSimpleValueType();
10957   // TODO: handle v16i8.
10958   if (VT.getSizeInBits() == 16) {
10959     SDValue Vec = Op.getOperand(0);
10960     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10961     if (Idx == 0)
10962       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10963                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10964                                      DAG.getBitcast(MVT::v4i32, Vec),
10965                                      Op.getOperand(1)));
10966     // Transform it so it match pextrw which produces a 32-bit result.
10967     MVT EltVT = MVT::i32;
10968     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10969                                   Op.getOperand(0), Op.getOperand(1));
10970     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10971                                   DAG.getValueType(VT));
10972     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10973   }
10974
10975   if (VT.getSizeInBits() == 32) {
10976     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10977     if (Idx == 0)
10978       return Op;
10979
10980     // SHUFPS the element to the lowest double word, then movss.
10981     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10982     MVT VVT = Op.getOperand(0).getSimpleValueType();
10983     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10984                                        DAG.getUNDEF(VVT), Mask);
10985     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10986                        DAG.getIntPtrConstant(0, dl));
10987   }
10988
10989   if (VT.getSizeInBits() == 64) {
10990     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10991     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10992     //        to match extract_elt for f64.
10993     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10994     if (Idx == 0)
10995       return Op;
10996
10997     // UNPCKHPD the element to the lowest double word, then movsd.
10998     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10999     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11000     int Mask[2] = { 1, -1 };
11001     MVT VVT = Op.getOperand(0).getSimpleValueType();
11002     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11003                                        DAG.getUNDEF(VVT), Mask);
11004     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11005                        DAG.getIntPtrConstant(0, dl));
11006   }
11007
11008   return SDValue();
11009 }
11010
11011 /// Insert one bit to mask vector, like v16i1 or v8i1.
11012 /// AVX-512 feature.
11013 SDValue
11014 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11015   SDLoc dl(Op);
11016   SDValue Vec = Op.getOperand(0);
11017   SDValue Elt = Op.getOperand(1);
11018   SDValue Idx = Op.getOperand(2);
11019   MVT VecVT = Vec.getSimpleValueType();
11020
11021   if (!isa<ConstantSDNode>(Idx)) {
11022     // Non constant index. Extend source and destination,
11023     // insert element and then truncate the result.
11024     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11025     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11026     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11027       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11028       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11029     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11030   }
11031
11032   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11033   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11034   if (IdxVal)
11035     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11036                            DAG.getConstant(IdxVal, dl, MVT::i8));
11037   if (Vec.getOpcode() == ISD::UNDEF)
11038     return EltInVec;
11039   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11040 }
11041
11042 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11043                                                   SelectionDAG &DAG) const {
11044   MVT VT = Op.getSimpleValueType();
11045   MVT EltVT = VT.getVectorElementType();
11046
11047   if (EltVT == MVT::i1)
11048     return InsertBitToMaskVector(Op, DAG);
11049
11050   SDLoc dl(Op);
11051   SDValue N0 = Op.getOperand(0);
11052   SDValue N1 = Op.getOperand(1);
11053   SDValue N2 = Op.getOperand(2);
11054   if (!isa<ConstantSDNode>(N2))
11055     return SDValue();
11056   auto *N2C = cast<ConstantSDNode>(N2);
11057   unsigned IdxVal = N2C->getZExtValue();
11058
11059   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11060   // into that, and then insert the subvector back into the result.
11061   if (VT.is256BitVector() || VT.is512BitVector()) {
11062     // With a 256-bit vector, we can insert into the zero element efficiently
11063     // using a blend if we have AVX or AVX2 and the right data type.
11064     if (VT.is256BitVector() && IdxVal == 0) {
11065       // TODO: It is worthwhile to cast integer to floating point and back
11066       // and incur a domain crossing penalty if that's what we'll end up
11067       // doing anyway after extracting to a 128-bit vector.
11068       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11069           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11070         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11071         N2 = DAG.getIntPtrConstant(1, dl);
11072         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11073       }
11074     }
11075
11076     // Get the desired 128-bit vector chunk.
11077     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11078
11079     // Insert the element into the desired chunk.
11080     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11081     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11082
11083     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11084                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11085
11086     // Insert the changed part back into the bigger vector
11087     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11088   }
11089   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11090
11091   if (Subtarget->hasSSE41()) {
11092     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11093       unsigned Opc;
11094       if (VT == MVT::v8i16) {
11095         Opc = X86ISD::PINSRW;
11096       } else {
11097         assert(VT == MVT::v16i8);
11098         Opc = X86ISD::PINSRB;
11099       }
11100
11101       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11102       // argument.
11103       if (N1.getValueType() != MVT::i32)
11104         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11105       if (N2.getValueType() != MVT::i32)
11106         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11107       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11108     }
11109
11110     if (EltVT == MVT::f32) {
11111       // Bits [7:6] of the constant are the source select. This will always be
11112       //   zero here. The DAG Combiner may combine an extract_elt index into
11113       //   these bits. For example (insert (extract, 3), 2) could be matched by
11114       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11115       // Bits [5:4] of the constant are the destination select. This is the
11116       //   value of the incoming immediate.
11117       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11118       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11119
11120       bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11121       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11122         // If this is an insertion of 32-bits into the low 32-bits of
11123         // a vector, we prefer to generate a blend with immediate rather
11124         // than an insertps. Blends are simpler operations in hardware and so
11125         // will always have equal or better performance than insertps.
11126         // But if optimizing for size and there's a load folding opportunity,
11127         // generate insertps because blendps does not have a 32-bit memory
11128         // operand form.
11129         N2 = DAG.getIntPtrConstant(1, dl);
11130         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11131         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11132       }
11133       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11134       // Create this as a scalar to vector..
11135       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11136       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11137     }
11138
11139     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11140       // PINSR* works with constant index.
11141       return Op;
11142     }
11143   }
11144
11145   if (EltVT == MVT::i8)
11146     return SDValue();
11147
11148   if (EltVT.getSizeInBits() == 16) {
11149     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11150     // as its second argument.
11151     if (N1.getValueType() != MVT::i32)
11152       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11153     if (N2.getValueType() != MVT::i32)
11154       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11155     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11156   }
11157   return SDValue();
11158 }
11159
11160 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11161   SDLoc dl(Op);
11162   MVT OpVT = Op.getSimpleValueType();
11163
11164   // If this is a 256-bit vector result, first insert into a 128-bit
11165   // vector and then insert into the 256-bit vector.
11166   if (!OpVT.is128BitVector()) {
11167     // Insert into a 128-bit vector.
11168     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11169     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11170                                  OpVT.getVectorNumElements() / SizeFactor);
11171
11172     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11173
11174     // Insert the 128-bit vector.
11175     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11176   }
11177
11178   if (OpVT == MVT::v1i64 &&
11179       Op.getOperand(0).getValueType() == MVT::i64)
11180     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11181
11182   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11183   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11184   return DAG.getBitcast(
11185       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11186 }
11187
11188 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11189 // a simple subregister reference or explicit instructions to grab
11190 // upper bits of a vector.
11191 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11192                                       SelectionDAG &DAG) {
11193   SDLoc dl(Op);
11194   SDValue In =  Op.getOperand(0);
11195   SDValue Idx = Op.getOperand(1);
11196   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11197   MVT ResVT   = Op.getSimpleValueType();
11198   MVT InVT    = In.getSimpleValueType();
11199
11200   if (Subtarget->hasFp256()) {
11201     if (ResVT.is128BitVector() &&
11202         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11203         isa<ConstantSDNode>(Idx)) {
11204       return Extract128BitVector(In, IdxVal, DAG, dl);
11205     }
11206     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11207         isa<ConstantSDNode>(Idx)) {
11208       return Extract256BitVector(In, IdxVal, DAG, dl);
11209     }
11210   }
11211   return SDValue();
11212 }
11213
11214 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11215 // simple superregister reference or explicit instructions to insert
11216 // the upper bits of a vector.
11217 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11218                                      SelectionDAG &DAG) {
11219   if (!Subtarget->hasAVX())
11220     return SDValue();
11221
11222   SDLoc dl(Op);
11223   SDValue Vec = Op.getOperand(0);
11224   SDValue SubVec = Op.getOperand(1);
11225   SDValue Idx = Op.getOperand(2);
11226
11227   if (!isa<ConstantSDNode>(Idx))
11228     return SDValue();
11229
11230   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11231   MVT OpVT = Op.getSimpleValueType();
11232   MVT SubVecVT = SubVec.getSimpleValueType();
11233
11234   // Fold two 16-byte subvector loads into one 32-byte load:
11235   // (insert_subvector (insert_subvector undef, (load addr), 0),
11236   //                   (load addr + 16), Elts/2)
11237   // --> load32 addr
11238   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11239       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11240       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11241       !Subtarget->isUnalignedMem32Slow()) {
11242     SDValue SubVec2 = Vec.getOperand(1);
11243     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11244       if (Idx2->getZExtValue() == 0) {
11245         SDValue Ops[] = { SubVec2, SubVec };
11246         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11247           return Ld;
11248       }
11249     }
11250   }
11251
11252   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11253       SubVecVT.is128BitVector())
11254     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11255
11256   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11257     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11258
11259   if (OpVT.getVectorElementType() == MVT::i1) {
11260     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11261       return Op;
11262     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11263     SDValue Undef = DAG.getUNDEF(OpVT);
11264     unsigned NumElems = OpVT.getVectorNumElements();
11265     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11266
11267     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11268       // Zero upper bits of the Vec
11269       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11270       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11271
11272       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11273                                  SubVec, ZeroIdx);
11274       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11275       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11276     }
11277     if (IdxVal == 0) {
11278       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11279                                  SubVec, ZeroIdx);
11280       // Zero upper bits of the Vec2
11281       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11282       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11283       // Zero lower bits of the Vec
11284       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11285       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11286       // Merge them together
11287       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11288     }
11289   }
11290   return SDValue();
11291 }
11292
11293 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11294 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11295 // one of the above mentioned nodes. It has to be wrapped because otherwise
11296 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11297 // be used to form addressing mode. These wrapped nodes will be selected
11298 // into MOV32ri.
11299 SDValue
11300 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11301   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11302
11303   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11304   // global base reg.
11305   unsigned char OpFlag = 0;
11306   unsigned WrapperKind = X86ISD::Wrapper;
11307   CodeModel::Model M = DAG.getTarget().getCodeModel();
11308
11309   if (Subtarget->isPICStyleRIPRel() &&
11310       (M == CodeModel::Small || M == CodeModel::Kernel))
11311     WrapperKind = X86ISD::WrapperRIP;
11312   else if (Subtarget->isPICStyleGOT())
11313     OpFlag = X86II::MO_GOTOFF;
11314   else if (Subtarget->isPICStyleStubPIC())
11315     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11316
11317   auto PtrVT = getPointerTy(DAG.getDataLayout());
11318   SDValue Result = DAG.getTargetConstantPool(
11319       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11320   SDLoc DL(CP);
11321   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11322   // With PIC, the address is actually $g + Offset.
11323   if (OpFlag) {
11324     Result =
11325         DAG.getNode(ISD::ADD, DL, PtrVT,
11326                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11327   }
11328
11329   return Result;
11330 }
11331
11332 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11333   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11334
11335   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11336   // global base reg.
11337   unsigned char OpFlag = 0;
11338   unsigned WrapperKind = X86ISD::Wrapper;
11339   CodeModel::Model M = DAG.getTarget().getCodeModel();
11340
11341   if (Subtarget->isPICStyleRIPRel() &&
11342       (M == CodeModel::Small || M == CodeModel::Kernel))
11343     WrapperKind = X86ISD::WrapperRIP;
11344   else if (Subtarget->isPICStyleGOT())
11345     OpFlag = X86II::MO_GOTOFF;
11346   else if (Subtarget->isPICStyleStubPIC())
11347     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11348
11349   auto PtrVT = getPointerTy(DAG.getDataLayout());
11350   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11351   SDLoc DL(JT);
11352   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11353
11354   // With PIC, the address is actually $g + Offset.
11355   if (OpFlag)
11356     Result =
11357         DAG.getNode(ISD::ADD, DL, PtrVT,
11358                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11359
11360   return Result;
11361 }
11362
11363 SDValue
11364 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11365   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11366
11367   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11368   // global base reg.
11369   unsigned char OpFlag = 0;
11370   unsigned WrapperKind = X86ISD::Wrapper;
11371   CodeModel::Model M = DAG.getTarget().getCodeModel();
11372
11373   if (Subtarget->isPICStyleRIPRel() &&
11374       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11375     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11376       OpFlag = X86II::MO_GOTPCREL;
11377     WrapperKind = X86ISD::WrapperRIP;
11378   } else if (Subtarget->isPICStyleGOT()) {
11379     OpFlag = X86II::MO_GOT;
11380   } else if (Subtarget->isPICStyleStubPIC()) {
11381     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11382   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11383     OpFlag = X86II::MO_DARWIN_NONLAZY;
11384   }
11385
11386   auto PtrVT = getPointerTy(DAG.getDataLayout());
11387   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11388
11389   SDLoc DL(Op);
11390   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11391
11392   // With PIC, the address is actually $g + Offset.
11393   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11394       !Subtarget->is64Bit()) {
11395     Result =
11396         DAG.getNode(ISD::ADD, DL, PtrVT,
11397                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11398   }
11399
11400   // For symbols that require a load from a stub to get the address, emit the
11401   // load.
11402   if (isGlobalStubReference(OpFlag))
11403     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11404                          MachinePointerInfo::getGOT(), false, false, false, 0);
11405
11406   return Result;
11407 }
11408
11409 SDValue
11410 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11411   // Create the TargetBlockAddressAddress node.
11412   unsigned char OpFlags =
11413     Subtarget->ClassifyBlockAddressReference();
11414   CodeModel::Model M = DAG.getTarget().getCodeModel();
11415   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11416   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11417   SDLoc dl(Op);
11418   auto PtrVT = getPointerTy(DAG.getDataLayout());
11419   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11420
11421   if (Subtarget->isPICStyleRIPRel() &&
11422       (M == CodeModel::Small || M == CodeModel::Kernel))
11423     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11424   else
11425     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11426
11427   // With PIC, the address is actually $g + Offset.
11428   if (isGlobalRelativeToPICBase(OpFlags)) {
11429     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11430                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11431   }
11432
11433   return Result;
11434 }
11435
11436 SDValue
11437 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11438                                       int64_t Offset, SelectionDAG &DAG) const {
11439   // Create the TargetGlobalAddress node, folding in the constant
11440   // offset if it is legal.
11441   unsigned char OpFlags =
11442       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11443   CodeModel::Model M = DAG.getTarget().getCodeModel();
11444   auto PtrVT = getPointerTy(DAG.getDataLayout());
11445   SDValue Result;
11446   if (OpFlags == X86II::MO_NO_FLAG &&
11447       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11448     // A direct static reference to a global.
11449     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11450     Offset = 0;
11451   } else {
11452     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11453   }
11454
11455   if (Subtarget->isPICStyleRIPRel() &&
11456       (M == CodeModel::Small || M == CodeModel::Kernel))
11457     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11458   else
11459     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11460
11461   // With PIC, the address is actually $g + Offset.
11462   if (isGlobalRelativeToPICBase(OpFlags)) {
11463     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11464                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11465   }
11466
11467   // For globals that require a load from a stub to get the address, emit the
11468   // load.
11469   if (isGlobalStubReference(OpFlags))
11470     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11471                          MachinePointerInfo::getGOT(), false, false, false, 0);
11472
11473   // If there was a non-zero offset that we didn't fold, create an explicit
11474   // addition for it.
11475   if (Offset != 0)
11476     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11477                          DAG.getConstant(Offset, dl, PtrVT));
11478
11479   return Result;
11480 }
11481
11482 SDValue
11483 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11484   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11485   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11486   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11487 }
11488
11489 static SDValue
11490 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11491            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11492            unsigned char OperandFlags, bool LocalDynamic = false) {
11493   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11494   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11495   SDLoc dl(GA);
11496   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11497                                            GA->getValueType(0),
11498                                            GA->getOffset(),
11499                                            OperandFlags);
11500
11501   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11502                                            : X86ISD::TLSADDR;
11503
11504   if (InFlag) {
11505     SDValue Ops[] = { Chain,  TGA, *InFlag };
11506     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11507   } else {
11508     SDValue Ops[]  = { Chain, TGA };
11509     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11510   }
11511
11512   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11513   MFI->setAdjustsStack(true);
11514   MFI->setHasCalls(true);
11515
11516   SDValue Flag = Chain.getValue(1);
11517   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11518 }
11519
11520 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11521 static SDValue
11522 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11523                                 const EVT PtrVT) {
11524   SDValue InFlag;
11525   SDLoc dl(GA);  // ? function entry point might be better
11526   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11527                                    DAG.getNode(X86ISD::GlobalBaseReg,
11528                                                SDLoc(), PtrVT), InFlag);
11529   InFlag = Chain.getValue(1);
11530
11531   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11532 }
11533
11534 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11535 static SDValue
11536 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11537                                 const EVT PtrVT) {
11538   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11539                     X86::RAX, X86II::MO_TLSGD);
11540 }
11541
11542 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11543                                            SelectionDAG &DAG,
11544                                            const EVT PtrVT,
11545                                            bool is64Bit) {
11546   SDLoc dl(GA);
11547
11548   // Get the start address of the TLS block for this module.
11549   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11550       .getInfo<X86MachineFunctionInfo>();
11551   MFI->incNumLocalDynamicTLSAccesses();
11552
11553   SDValue Base;
11554   if (is64Bit) {
11555     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11556                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11557   } else {
11558     SDValue InFlag;
11559     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11560         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11561     InFlag = Chain.getValue(1);
11562     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11563                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11564   }
11565
11566   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11567   // of Base.
11568
11569   // Build x@dtpoff.
11570   unsigned char OperandFlags = X86II::MO_DTPOFF;
11571   unsigned WrapperKind = X86ISD::Wrapper;
11572   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11573                                            GA->getValueType(0),
11574                                            GA->getOffset(), OperandFlags);
11575   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11576
11577   // Add x@dtpoff with the base.
11578   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11579 }
11580
11581 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11582 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11583                                    const EVT PtrVT, TLSModel::Model model,
11584                                    bool is64Bit, bool isPIC) {
11585   SDLoc dl(GA);
11586
11587   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11588   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11589                                                          is64Bit ? 257 : 256));
11590
11591   SDValue ThreadPointer =
11592       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11593                   MachinePointerInfo(Ptr), false, false, false, 0);
11594
11595   unsigned char OperandFlags = 0;
11596   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11597   // initialexec.
11598   unsigned WrapperKind = X86ISD::Wrapper;
11599   if (model == TLSModel::LocalExec) {
11600     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11601   } else if (model == TLSModel::InitialExec) {
11602     if (is64Bit) {
11603       OperandFlags = X86II::MO_GOTTPOFF;
11604       WrapperKind = X86ISD::WrapperRIP;
11605     } else {
11606       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11607     }
11608   } else {
11609     llvm_unreachable("Unexpected model");
11610   }
11611
11612   // emit "addl x@ntpoff,%eax" (local exec)
11613   // or "addl x@indntpoff,%eax" (initial exec)
11614   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11615   SDValue TGA =
11616       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11617                                  GA->getOffset(), OperandFlags);
11618   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11619
11620   if (model == TLSModel::InitialExec) {
11621     if (isPIC && !is64Bit) {
11622       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11623                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11624                            Offset);
11625     }
11626
11627     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11628                          MachinePointerInfo::getGOT(), false, false, false, 0);
11629   }
11630
11631   // The address of the thread local variable is the add of the thread
11632   // pointer with the offset of the variable.
11633   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11634 }
11635
11636 SDValue
11637 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11638
11639   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11640   const GlobalValue *GV = GA->getGlobal();
11641   auto PtrVT = getPointerTy(DAG.getDataLayout());
11642
11643   if (Subtarget->isTargetELF()) {
11644     if (DAG.getTarget().Options.EmulatedTLS)
11645       return LowerToTLSEmulatedModel(GA, DAG);
11646     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11647     switch (model) {
11648       case TLSModel::GeneralDynamic:
11649         if (Subtarget->is64Bit())
11650           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11651         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11652       case TLSModel::LocalDynamic:
11653         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11654                                            Subtarget->is64Bit());
11655       case TLSModel::InitialExec:
11656       case TLSModel::LocalExec:
11657         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11658                                    DAG.getTarget().getRelocationModel() ==
11659                                        Reloc::PIC_);
11660     }
11661     llvm_unreachable("Unknown TLS model.");
11662   }
11663
11664   if (Subtarget->isTargetDarwin()) {
11665     // Darwin only has one model of TLS.  Lower to that.
11666     unsigned char OpFlag = 0;
11667     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11668                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11669
11670     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11671     // global base reg.
11672     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11673                  !Subtarget->is64Bit();
11674     if (PIC32)
11675       OpFlag = X86II::MO_TLVP_PIC_BASE;
11676     else
11677       OpFlag = X86II::MO_TLVP;
11678     SDLoc DL(Op);
11679     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11680                                                 GA->getValueType(0),
11681                                                 GA->getOffset(), OpFlag);
11682     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11683
11684     // With PIC32, the address is actually $g + Offset.
11685     if (PIC32)
11686       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11687                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11688                            Offset);
11689
11690     // Lowering the machine isd will make sure everything is in the right
11691     // location.
11692     SDValue Chain = DAG.getEntryNode();
11693     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11694     SDValue Args[] = { Chain, Offset };
11695     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11696
11697     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11698     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11699     MFI->setAdjustsStack(true);
11700
11701     // And our return value (tls address) is in the standard call return value
11702     // location.
11703     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11704     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11705   }
11706
11707   if (Subtarget->isTargetKnownWindowsMSVC() ||
11708       Subtarget->isTargetWindowsGNU()) {
11709     // Just use the implicit TLS architecture
11710     // Need to generate someting similar to:
11711     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11712     //                                  ; from TEB
11713     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11714     //   mov     rcx, qword [rdx+rcx*8]
11715     //   mov     eax, .tls$:tlsvar
11716     //   [rax+rcx] contains the address
11717     // Windows 64bit: gs:0x58
11718     // Windows 32bit: fs:__tls_array
11719
11720     SDLoc dl(GA);
11721     SDValue Chain = DAG.getEntryNode();
11722
11723     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11724     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11725     // use its literal value of 0x2C.
11726     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11727                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11728                                                              256)
11729                                         : Type::getInt32PtrTy(*DAG.getContext(),
11730                                                               257));
11731
11732     SDValue TlsArray = Subtarget->is64Bit()
11733                            ? DAG.getIntPtrConstant(0x58, dl)
11734                            : (Subtarget->isTargetWindowsGNU()
11735                                   ? DAG.getIntPtrConstant(0x2C, dl)
11736                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11737
11738     SDValue ThreadPointer =
11739         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11740                     false, false, 0);
11741
11742     SDValue res;
11743     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11744       res = ThreadPointer;
11745     } else {
11746       // Load the _tls_index variable
11747       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11748       if (Subtarget->is64Bit())
11749         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11750                              MachinePointerInfo(), MVT::i32, false, false,
11751                              false, 0);
11752       else
11753         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11754                           false, false, 0);
11755
11756       auto &DL = DAG.getDataLayout();
11757       SDValue Scale =
11758           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11759       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11760
11761       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11762     }
11763
11764     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11765                       false, 0);
11766
11767     // Get the offset of start of .tls section
11768     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11769                                              GA->getValueType(0),
11770                                              GA->getOffset(), X86II::MO_SECREL);
11771     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11772
11773     // The address of the thread local variable is the add of the thread
11774     // pointer with the offset of the variable.
11775     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11776   }
11777
11778   llvm_unreachable("TLS not implemented for this target.");
11779 }
11780
11781 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11782 /// and take a 2 x i32 value to shift plus a shift amount.
11783 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11784   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11785   MVT VT = Op.getSimpleValueType();
11786   unsigned VTBits = VT.getSizeInBits();
11787   SDLoc dl(Op);
11788   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11789   SDValue ShOpLo = Op.getOperand(0);
11790   SDValue ShOpHi = Op.getOperand(1);
11791   SDValue ShAmt  = Op.getOperand(2);
11792   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11793   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11794   // during isel.
11795   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11796                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11797   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11798                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11799                        : DAG.getConstant(0, dl, VT);
11800
11801   SDValue Tmp2, Tmp3;
11802   if (Op.getOpcode() == ISD::SHL_PARTS) {
11803     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11804     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11805   } else {
11806     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11807     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11808   }
11809
11810   // If the shift amount is larger or equal than the width of a part we can't
11811   // rely on the results of shld/shrd. Insert a test and select the appropriate
11812   // values for large shift amounts.
11813   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11814                                 DAG.getConstant(VTBits, dl, MVT::i8));
11815   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11816                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11817
11818   SDValue Hi, Lo;
11819   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11820   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11821   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11822
11823   if (Op.getOpcode() == ISD::SHL_PARTS) {
11824     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11825     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11826   } else {
11827     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11828     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11829   }
11830
11831   SDValue Ops[2] = { Lo, Hi };
11832   return DAG.getMergeValues(Ops, dl);
11833 }
11834
11835 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11836                                            SelectionDAG &DAG) const {
11837   SDValue Src = Op.getOperand(0);
11838   MVT SrcVT = Src.getSimpleValueType();
11839   MVT VT = Op.getSimpleValueType();
11840   SDLoc dl(Op);
11841
11842   if (SrcVT.isVector()) {
11843     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11844       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11845                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11846                          DAG.getUNDEF(SrcVT)));
11847     }
11848     if (SrcVT.getVectorElementType() == MVT::i1) {
11849       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11850       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11851                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11852     }
11853     return SDValue();
11854   }
11855
11856   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11857          "Unknown SINT_TO_FP to lower!");
11858
11859   // These are really Legal; return the operand so the caller accepts it as
11860   // Legal.
11861   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11862     return Op;
11863   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11864       Subtarget->is64Bit()) {
11865     return Op;
11866   }
11867
11868   unsigned Size = SrcVT.getSizeInBits()/8;
11869   MachineFunction &MF = DAG.getMachineFunction();
11870   auto PtrVT = getPointerTy(MF.getDataLayout());
11871   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11872   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11873   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11874                                StackSlot,
11875                                MachinePointerInfo::getFixedStack(SSFI),
11876                                false, false, 0);
11877   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11878 }
11879
11880 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11881                                      SDValue StackSlot,
11882                                      SelectionDAG &DAG) const {
11883   // Build the FILD
11884   SDLoc DL(Op);
11885   SDVTList Tys;
11886   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11887   if (useSSE)
11888     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11889   else
11890     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11891
11892   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11893
11894   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11895   MachineMemOperand *MMO;
11896   if (FI) {
11897     int SSFI = FI->getIndex();
11898     MMO =
11899       DAG.getMachineFunction()
11900       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11901                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11902   } else {
11903     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11904     StackSlot = StackSlot.getOperand(1);
11905   }
11906   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11907   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11908                                            X86ISD::FILD, DL,
11909                                            Tys, Ops, SrcVT, MMO);
11910
11911   if (useSSE) {
11912     Chain = Result.getValue(1);
11913     SDValue InFlag = Result.getValue(2);
11914
11915     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11916     // shouldn't be necessary except that RFP cannot be live across
11917     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11918     MachineFunction &MF = DAG.getMachineFunction();
11919     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11920     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11921     auto PtrVT = getPointerTy(MF.getDataLayout());
11922     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11923     Tys = DAG.getVTList(MVT::Other);
11924     SDValue Ops[] = {
11925       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11926     };
11927     MachineMemOperand *MMO =
11928       DAG.getMachineFunction()
11929       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11930                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11931
11932     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11933                                     Ops, Op.getValueType(), MMO);
11934     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11935                          MachinePointerInfo::getFixedStack(SSFI),
11936                          false, false, false, 0);
11937   }
11938
11939   return Result;
11940 }
11941
11942 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11943 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11944                                                SelectionDAG &DAG) const {
11945   // This algorithm is not obvious. Here it is what we're trying to output:
11946   /*
11947      movq       %rax,  %xmm0
11948      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11949      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11950      #ifdef __SSE3__
11951        haddpd   %xmm0, %xmm0
11952      #else
11953        pshufd   $0x4e, %xmm0, %xmm1
11954        addpd    %xmm1, %xmm0
11955      #endif
11956   */
11957
11958   SDLoc dl(Op);
11959   LLVMContext *Context = DAG.getContext();
11960
11961   // Build some magic constants.
11962   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11963   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11964   auto PtrVT = getPointerTy(DAG.getDataLayout());
11965   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11966
11967   SmallVector<Constant*,2> CV1;
11968   CV1.push_back(
11969     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11970                                       APInt(64, 0x4330000000000000ULL))));
11971   CV1.push_back(
11972     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11973                                       APInt(64, 0x4530000000000000ULL))));
11974   Constant *C1 = ConstantVector::get(CV1);
11975   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11976
11977   // Load the 64-bit value into an XMM register.
11978   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11979                             Op.getOperand(0));
11980   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11981                               MachinePointerInfo::getConstantPool(),
11982                               false, false, false, 16);
11983   SDValue Unpck1 =
11984       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11985
11986   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11987                               MachinePointerInfo::getConstantPool(),
11988                               false, false, false, 16);
11989   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11990   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11991   SDValue Result;
11992
11993   if (Subtarget->hasSSE3()) {
11994     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11995     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11996   } else {
11997     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11998     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11999                                            S2F, 0x4E, DAG);
12000     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12001                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12002   }
12003
12004   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12005                      DAG.getIntPtrConstant(0, dl));
12006 }
12007
12008 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12009 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12010                                                SelectionDAG &DAG) const {
12011   SDLoc dl(Op);
12012   // FP constant to bias correct the final result.
12013   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12014                                    MVT::f64);
12015
12016   // Load the 32-bit value into an XMM register.
12017   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12018                              Op.getOperand(0));
12019
12020   // Zero out the upper parts of the register.
12021   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12022
12023   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12024                      DAG.getBitcast(MVT::v2f64, Load),
12025                      DAG.getIntPtrConstant(0, dl));
12026
12027   // Or the load with the bias.
12028   SDValue Or = DAG.getNode(
12029       ISD::OR, dl, MVT::v2i64,
12030       DAG.getBitcast(MVT::v2i64,
12031                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12032       DAG.getBitcast(MVT::v2i64,
12033                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12034   Or =
12035       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12036                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12037
12038   // Subtract the bias.
12039   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12040
12041   // Handle final rounding.
12042   EVT DestVT = Op.getValueType();
12043
12044   if (DestVT.bitsLT(MVT::f64))
12045     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12046                        DAG.getIntPtrConstant(0, dl));
12047   if (DestVT.bitsGT(MVT::f64))
12048     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12049
12050   // Handle final rounding.
12051   return Sub;
12052 }
12053
12054 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12055                                      const X86Subtarget &Subtarget) {
12056   // The algorithm is the following:
12057   // #ifdef __SSE4_1__
12058   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12059   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12060   //                                 (uint4) 0x53000000, 0xaa);
12061   // #else
12062   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12063   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12064   // #endif
12065   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12066   //     return (float4) lo + fhi;
12067
12068   SDLoc DL(Op);
12069   SDValue V = Op->getOperand(0);
12070   EVT VecIntVT = V.getValueType();
12071   bool Is128 = VecIntVT == MVT::v4i32;
12072   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12073   // If we convert to something else than the supported type, e.g., to v4f64,
12074   // abort early.
12075   if (VecFloatVT != Op->getValueType(0))
12076     return SDValue();
12077
12078   unsigned NumElts = VecIntVT.getVectorNumElements();
12079   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12080          "Unsupported custom type");
12081   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12082
12083   // In the #idef/#else code, we have in common:
12084   // - The vector of constants:
12085   // -- 0x4b000000
12086   // -- 0x53000000
12087   // - A shift:
12088   // -- v >> 16
12089
12090   // Create the splat vector for 0x4b000000.
12091   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12092   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12093                            CstLow, CstLow, CstLow, CstLow};
12094   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12095                                   makeArrayRef(&CstLowArray[0], NumElts));
12096   // Create the splat vector for 0x53000000.
12097   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12098   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12099                             CstHigh, CstHigh, CstHigh, CstHigh};
12100   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12101                                    makeArrayRef(&CstHighArray[0], NumElts));
12102
12103   // Create the right shift.
12104   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12105   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12106                              CstShift, CstShift, CstShift, CstShift};
12107   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12108                                     makeArrayRef(&CstShiftArray[0], NumElts));
12109   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12110
12111   SDValue Low, High;
12112   if (Subtarget.hasSSE41()) {
12113     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12114     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12115     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12116     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12117     // Low will be bitcasted right away, so do not bother bitcasting back to its
12118     // original type.
12119     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12120                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12121     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12122     //                                 (uint4) 0x53000000, 0xaa);
12123     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12124     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12125     // High will be bitcasted right away, so do not bother bitcasting back to
12126     // its original type.
12127     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12128                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12129   } else {
12130     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12131     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12132                                      CstMask, CstMask, CstMask);
12133     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12134     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12135     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12136
12137     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12138     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12139   }
12140
12141   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12142   SDValue CstFAdd = DAG.getConstantFP(
12143       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12144   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12145                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12146   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12147                                    makeArrayRef(&CstFAddArray[0], NumElts));
12148
12149   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12150   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12151   SDValue FHigh =
12152       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12153   //     return (float4) lo + fhi;
12154   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12155   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12156 }
12157
12158 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12159                                                SelectionDAG &DAG) const {
12160   SDValue N0 = Op.getOperand(0);
12161   MVT SVT = N0.getSimpleValueType();
12162   SDLoc dl(Op);
12163
12164   switch (SVT.SimpleTy) {
12165   default:
12166     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12167   case MVT::v4i8:
12168   case MVT::v4i16:
12169   case MVT::v8i8:
12170   case MVT::v8i16: {
12171     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12172     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12173                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12174   }
12175   case MVT::v4i32:
12176   case MVT::v8i32:
12177     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12178   case MVT::v16i8:
12179   case MVT::v16i16:
12180     if (Subtarget->hasAVX512())
12181       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12182                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12183   }
12184   llvm_unreachable(nullptr);
12185 }
12186
12187 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12188                                            SelectionDAG &DAG) const {
12189   SDValue N0 = Op.getOperand(0);
12190   SDLoc dl(Op);
12191   auto PtrVT = getPointerTy(DAG.getDataLayout());
12192
12193   if (Op.getValueType().isVector())
12194     return lowerUINT_TO_FP_vec(Op, DAG);
12195
12196   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12197   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12198   // the optimization here.
12199   if (DAG.SignBitIsZero(N0))
12200     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12201
12202   MVT SrcVT = N0.getSimpleValueType();
12203   MVT DstVT = Op.getSimpleValueType();
12204   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12205     return LowerUINT_TO_FP_i64(Op, DAG);
12206   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12207     return LowerUINT_TO_FP_i32(Op, DAG);
12208   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12209     return SDValue();
12210
12211   // Make a 64-bit buffer, and use it to build an FILD.
12212   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12213   if (SrcVT == MVT::i32) {
12214     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12215     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12216     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12217                                   StackSlot, MachinePointerInfo(),
12218                                   false, false, 0);
12219     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12220                                   OffsetSlot, MachinePointerInfo(),
12221                                   false, false, 0);
12222     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12223     return Fild;
12224   }
12225
12226   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12227   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12228                                StackSlot, MachinePointerInfo(),
12229                                false, false, 0);
12230   // For i64 source, we need to add the appropriate power of 2 if the input
12231   // was negative.  This is the same as the optimization in
12232   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12233   // we must be careful to do the computation in x87 extended precision, not
12234   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12235   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12236   MachineMemOperand *MMO =
12237     DAG.getMachineFunction()
12238     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12239                           MachineMemOperand::MOLoad, 8, 8);
12240
12241   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12242   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12243   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12244                                          MVT::i64, MMO);
12245
12246   APInt FF(32, 0x5F800000ULL);
12247
12248   // Check whether the sign bit is set.
12249   SDValue SignSet = DAG.getSetCC(
12250       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12251       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12252
12253   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12254   SDValue FudgePtr = DAG.getConstantPool(
12255       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12256
12257   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12258   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12259   SDValue Four = DAG.getIntPtrConstant(4, dl);
12260   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12261                                Zero, Four);
12262   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12263
12264   // Load the value out, extending it from f32 to f80.
12265   // FIXME: Avoid the extend by constructing the right constant pool?
12266   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12267                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12268                                  MVT::f32, false, false, false, 4);
12269   // Extend everything to 80 bits to force it to be done on x87.
12270   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12271   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12272                      DAG.getIntPtrConstant(0, dl));
12273 }
12274
12275 std::pair<SDValue,SDValue>
12276 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12277                                     bool IsSigned, bool IsReplace) const {
12278   SDLoc DL(Op);
12279
12280   EVT DstTy = Op.getValueType();
12281   auto PtrVT = getPointerTy(DAG.getDataLayout());
12282
12283   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12284     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12285     DstTy = MVT::i64;
12286   }
12287
12288   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12289          DstTy.getSimpleVT() >= MVT::i16 &&
12290          "Unknown FP_TO_INT to lower!");
12291
12292   // These are really Legal.
12293   if (DstTy == MVT::i32 &&
12294       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12295     return std::make_pair(SDValue(), SDValue());
12296   if (Subtarget->is64Bit() &&
12297       DstTy == MVT::i64 &&
12298       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12299     return std::make_pair(SDValue(), SDValue());
12300
12301   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12302   // stack slot, or into the FTOL runtime function.
12303   MachineFunction &MF = DAG.getMachineFunction();
12304   unsigned MemSize = DstTy.getSizeInBits()/8;
12305   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12306   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12307
12308   unsigned Opc;
12309   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12310     Opc = X86ISD::WIN_FTOL;
12311   else
12312     switch (DstTy.getSimpleVT().SimpleTy) {
12313     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12314     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12315     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12316     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12317     }
12318
12319   SDValue Chain = DAG.getEntryNode();
12320   SDValue Value = Op.getOperand(0);
12321   EVT TheVT = Op.getOperand(0).getValueType();
12322   // FIXME This causes a redundant load/store if the SSE-class value is already
12323   // in memory, such as if it is on the callstack.
12324   if (isScalarFPTypeInSSEReg(TheVT)) {
12325     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12326     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12327                          MachinePointerInfo::getFixedStack(SSFI),
12328                          false, false, 0);
12329     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12330     SDValue Ops[] = {
12331       Chain, StackSlot, DAG.getValueType(TheVT)
12332     };
12333
12334     MachineMemOperand *MMO =
12335       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12336                               MachineMemOperand::MOLoad, MemSize, MemSize);
12337     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12338     Chain = Value.getValue(1);
12339     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12340     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12341   }
12342
12343   MachineMemOperand *MMO =
12344     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12345                             MachineMemOperand::MOStore, MemSize, MemSize);
12346
12347   if (Opc != X86ISD::WIN_FTOL) {
12348     // Build the FP_TO_INT*_IN_MEM
12349     SDValue Ops[] = { Chain, Value, StackSlot };
12350     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12351                                            Ops, DstTy, MMO);
12352     return std::make_pair(FIST, StackSlot);
12353   } else {
12354     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12355       DAG.getVTList(MVT::Other, MVT::Glue),
12356       Chain, Value);
12357     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12358       MVT::i32, ftol.getValue(1));
12359     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12360       MVT::i32, eax.getValue(2));
12361     SDValue Ops[] = { eax, edx };
12362     SDValue pair = IsReplace
12363       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12364       : DAG.getMergeValues(Ops, DL);
12365     return std::make_pair(pair, SDValue());
12366   }
12367 }
12368
12369 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12370                               const X86Subtarget *Subtarget) {
12371   MVT VT = Op->getSimpleValueType(0);
12372   SDValue In = Op->getOperand(0);
12373   MVT InVT = In.getSimpleValueType();
12374   SDLoc dl(Op);
12375
12376   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12377     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12378
12379   // Optimize vectors in AVX mode:
12380   //
12381   //   v8i16 -> v8i32
12382   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12383   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12384   //   Concat upper and lower parts.
12385   //
12386   //   v4i32 -> v4i64
12387   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12388   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12389   //   Concat upper and lower parts.
12390   //
12391
12392   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12393       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12394       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12395     return SDValue();
12396
12397   if (Subtarget->hasInt256())
12398     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12399
12400   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12401   SDValue Undef = DAG.getUNDEF(InVT);
12402   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12403   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12404   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12405
12406   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12407                              VT.getVectorNumElements()/2);
12408
12409   OpLo = DAG.getBitcast(HVT, OpLo);
12410   OpHi = DAG.getBitcast(HVT, OpHi);
12411
12412   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12413 }
12414
12415 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12416                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12417   MVT VT = Op->getSimpleValueType(0);
12418   SDValue In = Op->getOperand(0);
12419   MVT InVT = In.getSimpleValueType();
12420   SDLoc DL(Op);
12421   unsigned int NumElts = VT.getVectorNumElements();
12422   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12423     return SDValue();
12424
12425   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12426     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12427
12428   assert(InVT.getVectorElementType() == MVT::i1);
12429   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12430   SDValue One =
12431    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12432   SDValue Zero =
12433    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12434
12435   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12436   if (VT.is512BitVector())
12437     return V;
12438   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12439 }
12440
12441 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12442                                SelectionDAG &DAG) {
12443   if (Subtarget->hasFp256())
12444     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12445       return Res;
12446
12447   return SDValue();
12448 }
12449
12450 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12451                                 SelectionDAG &DAG) {
12452   SDLoc DL(Op);
12453   MVT VT = Op.getSimpleValueType();
12454   SDValue In = Op.getOperand(0);
12455   MVT SVT = In.getSimpleValueType();
12456
12457   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12458     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12459
12460   if (Subtarget->hasFp256())
12461     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12462       return Res;
12463
12464   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12465          VT.getVectorNumElements() != SVT.getVectorNumElements());
12466   return SDValue();
12467 }
12468
12469 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12470   SDLoc DL(Op);
12471   MVT VT = Op.getSimpleValueType();
12472   SDValue In = Op.getOperand(0);
12473   MVT InVT = In.getSimpleValueType();
12474
12475   if (VT == MVT::i1) {
12476     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12477            "Invalid scalar TRUNCATE operation");
12478     if (InVT.getSizeInBits() >= 32)
12479       return SDValue();
12480     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12481     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12482   }
12483   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12484          "Invalid TRUNCATE operation");
12485
12486   // move vector to mask - truncate solution for SKX
12487   if (VT.getVectorElementType() == MVT::i1) {
12488     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12489         Subtarget->hasBWI())
12490       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12491     if ((InVT.is256BitVector() || InVT.is128BitVector())
12492         && InVT.getScalarSizeInBits() <= 16 &&
12493         Subtarget->hasBWI() && Subtarget->hasVLX())
12494       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12495     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12496         Subtarget->hasDQI())
12497       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12498     if ((InVT.is256BitVector() || InVT.is128BitVector())
12499         && InVT.getScalarSizeInBits() >= 32 &&
12500         Subtarget->hasDQI() && Subtarget->hasVLX())
12501       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12502   }
12503
12504   if (VT.getVectorElementType() == MVT::i1) {
12505     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12506     unsigned NumElts = InVT.getVectorNumElements();
12507     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12508     if (InVT.getSizeInBits() < 512) {
12509       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12510       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12511       InVT = ExtVT;
12512     }
12513
12514     SDValue OneV =
12515      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12516     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12517     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12518   }
12519
12520   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12521   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12522       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12523     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12524
12525   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12526     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12527     if (Subtarget->hasInt256()) {
12528       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12529       In = DAG.getBitcast(MVT::v8i32, In);
12530       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12531                                 ShufMask);
12532       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12533                          DAG.getIntPtrConstant(0, DL));
12534     }
12535
12536     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12537                                DAG.getIntPtrConstant(0, DL));
12538     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12539                                DAG.getIntPtrConstant(2, DL));
12540     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12541     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12542     static const int ShufMask[] = {0, 2, 4, 6};
12543     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12544   }
12545
12546   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12547     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12548     if (Subtarget->hasInt256()) {
12549       In = DAG.getBitcast(MVT::v32i8, In);
12550
12551       SmallVector<SDValue,32> pshufbMask;
12552       for (unsigned i = 0; i < 2; ++i) {
12553         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12554         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12555         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12556         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12557         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12558         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12559         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12560         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12561         for (unsigned j = 0; j < 8; ++j)
12562           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12563       }
12564       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12565       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12566       In = DAG.getBitcast(MVT::v4i64, In);
12567
12568       static const int ShufMask[] = {0,  2,  -1,  -1};
12569       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12570                                 &ShufMask[0]);
12571       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12572                        DAG.getIntPtrConstant(0, DL));
12573       return DAG.getBitcast(VT, In);
12574     }
12575
12576     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12577                                DAG.getIntPtrConstant(0, DL));
12578
12579     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12580                                DAG.getIntPtrConstant(4, DL));
12581
12582     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12583     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12584
12585     // The PSHUFB mask:
12586     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12587                                    -1, -1, -1, -1, -1, -1, -1, -1};
12588
12589     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12590     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12591     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12592
12593     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12594     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12595
12596     // The MOVLHPS Mask:
12597     static const int ShufMask2[] = {0, 1, 4, 5};
12598     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12599     return DAG.getBitcast(MVT::v8i16, res);
12600   }
12601
12602   // Handle truncation of V256 to V128 using shuffles.
12603   if (!VT.is128BitVector() || !InVT.is256BitVector())
12604     return SDValue();
12605
12606   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12607
12608   unsigned NumElems = VT.getVectorNumElements();
12609   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12610
12611   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12612   // Prepare truncation shuffle mask
12613   for (unsigned i = 0; i != NumElems; ++i)
12614     MaskVec[i] = i * 2;
12615   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12616                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12617   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12618                      DAG.getIntPtrConstant(0, DL));
12619 }
12620
12621 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12622                                            SelectionDAG &DAG) const {
12623   assert(!Op.getSimpleValueType().isVector());
12624
12625   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12626     /*IsSigned=*/ true, /*IsReplace=*/ false);
12627   SDValue FIST = Vals.first, StackSlot = Vals.second;
12628   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12629   if (!FIST.getNode()) return Op;
12630
12631   if (StackSlot.getNode())
12632     // Load the result.
12633     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12634                        FIST, StackSlot, MachinePointerInfo(),
12635                        false, false, false, 0);
12636
12637   // The node is the result.
12638   return FIST;
12639 }
12640
12641 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12642                                            SelectionDAG &DAG) const {
12643   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12644     /*IsSigned=*/ false, /*IsReplace=*/ false);
12645   SDValue FIST = Vals.first, StackSlot = Vals.second;
12646   assert(FIST.getNode() && "Unexpected failure");
12647
12648   if (StackSlot.getNode())
12649     // Load the result.
12650     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12651                        FIST, StackSlot, MachinePointerInfo(),
12652                        false, false, false, 0);
12653
12654   // The node is the result.
12655   return FIST;
12656 }
12657
12658 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12659   SDLoc DL(Op);
12660   MVT VT = Op.getSimpleValueType();
12661   SDValue In = Op.getOperand(0);
12662   MVT SVT = In.getSimpleValueType();
12663
12664   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12665
12666   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12667                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12668                                  In, DAG.getUNDEF(SVT)));
12669 }
12670
12671 /// The only differences between FABS and FNEG are the mask and the logic op.
12672 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12673 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12674   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12675          "Wrong opcode for lowering FABS or FNEG.");
12676
12677   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12678
12679   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12680   // into an FNABS. We'll lower the FABS after that if it is still in use.
12681   if (IsFABS)
12682     for (SDNode *User : Op->uses())
12683       if (User->getOpcode() == ISD::FNEG)
12684         return Op;
12685
12686   SDLoc dl(Op);
12687   MVT VT = Op.getSimpleValueType();
12688
12689   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12690   // decide if we should generate a 16-byte constant mask when we only need 4 or
12691   // 8 bytes for the scalar case.
12692
12693   MVT LogicVT;
12694   MVT EltVT;
12695   unsigned NumElts;
12696   
12697   if (VT.isVector()) {
12698     LogicVT = VT;
12699     EltVT = VT.getVectorElementType();
12700     NumElts = VT.getVectorNumElements();
12701   } else {
12702     // There are no scalar bitwise logical SSE/AVX instructions, so we
12703     // generate a 16-byte vector constant and logic op even for the scalar case.
12704     // Using a 16-byte mask allows folding the load of the mask with
12705     // the logic op, so it can save (~4 bytes) on code size.
12706     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12707     EltVT = VT;
12708     NumElts = (VT == MVT::f64) ? 2 : 4;
12709   }
12710
12711   unsigned EltBits = EltVT.getSizeInBits();
12712   LLVMContext *Context = DAG.getContext();
12713   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12714   APInt MaskElt =
12715     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12716   Constant *C = ConstantInt::get(*Context, MaskElt);
12717   C = ConstantVector::getSplat(NumElts, C);
12718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12719   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12720   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12721   SDValue Mask = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12722                              MachinePointerInfo::getConstantPool(),
12723                              false, false, false, Alignment);
12724
12725   SDValue Op0 = Op.getOperand(0);
12726   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12727   unsigned LogicOp =
12728     IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12729   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12730
12731   if (VT.isVector())
12732     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12733
12734   // For the scalar case extend to a 128-bit vector, perform the logic op,
12735   // and extract the scalar result back out.
12736   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12737   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12738   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12739                      DAG.getIntPtrConstant(0, dl));
12740 }
12741
12742 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12743   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12744   LLVMContext *Context = DAG.getContext();
12745   SDValue Op0 = Op.getOperand(0);
12746   SDValue Op1 = Op.getOperand(1);
12747   SDLoc dl(Op);
12748   MVT VT = Op.getSimpleValueType();
12749   MVT SrcVT = Op1.getSimpleValueType();
12750
12751   // If second operand is smaller, extend it first.
12752   if (SrcVT.bitsLT(VT)) {
12753     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12754     SrcVT = VT;
12755   }
12756   // And if it is bigger, shrink it first.
12757   if (SrcVT.bitsGT(VT)) {
12758     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12759     SrcVT = VT;
12760   }
12761
12762   // At this point the operands and the result should have the same
12763   // type, and that won't be f80 since that is not custom lowered.
12764
12765   const fltSemantics &Sem =
12766       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12767   const unsigned SizeInBits = VT.getSizeInBits();
12768
12769   SmallVector<Constant *, 4> CV(
12770       VT == MVT::f64 ? 2 : 4,
12771       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12772
12773   // First, clear all bits but the sign bit from the second operand (sign).
12774   CV[0] = ConstantFP::get(*Context,
12775                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12776   Constant *C = ConstantVector::get(CV);
12777   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12778   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12779
12780   // Perform all logic operations as 16-byte vectors because there are no
12781   // scalar FP logic instructions in SSE. This allows load folding of the
12782   // constants into the logic instructions.
12783   MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12784   SDValue Mask1 = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12785                               MachinePointerInfo::getConstantPool(),
12786                               false, false, false, 16);
12787   Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12788   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12789
12790   // Next, clear the sign bit from the first operand (magnitude).
12791   // If it's a constant, we can clear it here.
12792   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12793     APFloat APF = Op0CN->getValueAPF();
12794     // If the magnitude is a positive zero, the sign bit alone is enough.
12795     if (APF.isPosZero())
12796       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12797                          DAG.getIntPtrConstant(0, dl));
12798     APF.clearSign();
12799     CV[0] = ConstantFP::get(*Context, APF);
12800   } else {
12801     CV[0] = ConstantFP::get(
12802         *Context,
12803         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12804   }
12805   C = ConstantVector::get(CV);
12806   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12807   SDValue Val = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12808                             MachinePointerInfo::getConstantPool(),
12809                             false, false, false, 16);
12810   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12811   if (!isa<ConstantFPSDNode>(Op0)) {
12812     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12813     Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12814   }
12815   // OR the magnitude value with the sign bit.
12816   Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12817   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12818                      DAG.getIntPtrConstant(0, dl));
12819 }
12820
12821 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12822   SDValue N0 = Op.getOperand(0);
12823   SDLoc dl(Op);
12824   MVT VT = Op.getSimpleValueType();
12825
12826   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12827   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12828                                   DAG.getConstant(1, dl, VT));
12829   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12830 }
12831
12832 // Check whether an OR'd tree is PTEST-able.
12833 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12834                                       SelectionDAG &DAG) {
12835   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12836
12837   if (!Subtarget->hasSSE41())
12838     return SDValue();
12839
12840   if (!Op->hasOneUse())
12841     return SDValue();
12842
12843   SDNode *N = Op.getNode();
12844   SDLoc DL(N);
12845
12846   SmallVector<SDValue, 8> Opnds;
12847   DenseMap<SDValue, unsigned> VecInMap;
12848   SmallVector<SDValue, 8> VecIns;
12849   EVT VT = MVT::Other;
12850
12851   // Recognize a special case where a vector is casted into wide integer to
12852   // test all 0s.
12853   Opnds.push_back(N->getOperand(0));
12854   Opnds.push_back(N->getOperand(1));
12855
12856   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12857     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12858     // BFS traverse all OR'd operands.
12859     if (I->getOpcode() == ISD::OR) {
12860       Opnds.push_back(I->getOperand(0));
12861       Opnds.push_back(I->getOperand(1));
12862       // Re-evaluate the number of nodes to be traversed.
12863       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12864       continue;
12865     }
12866
12867     // Quit if a non-EXTRACT_VECTOR_ELT
12868     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12869       return SDValue();
12870
12871     // Quit if without a constant index.
12872     SDValue Idx = I->getOperand(1);
12873     if (!isa<ConstantSDNode>(Idx))
12874       return SDValue();
12875
12876     SDValue ExtractedFromVec = I->getOperand(0);
12877     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12878     if (M == VecInMap.end()) {
12879       VT = ExtractedFromVec.getValueType();
12880       // Quit if not 128/256-bit vector.
12881       if (!VT.is128BitVector() && !VT.is256BitVector())
12882         return SDValue();
12883       // Quit if not the same type.
12884       if (VecInMap.begin() != VecInMap.end() &&
12885           VT != VecInMap.begin()->first.getValueType())
12886         return SDValue();
12887       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12888       VecIns.push_back(ExtractedFromVec);
12889     }
12890     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12891   }
12892
12893   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12894          "Not extracted from 128-/256-bit vector.");
12895
12896   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12897
12898   for (DenseMap<SDValue, unsigned>::const_iterator
12899         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12900     // Quit if not all elements are used.
12901     if (I->second != FullMask)
12902       return SDValue();
12903   }
12904
12905   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12906
12907   // Cast all vectors into TestVT for PTEST.
12908   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12909     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12910
12911   // If more than one full vectors are evaluated, OR them first before PTEST.
12912   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12913     // Each iteration will OR 2 nodes and append the result until there is only
12914     // 1 node left, i.e. the final OR'd value of all vectors.
12915     SDValue LHS = VecIns[Slot];
12916     SDValue RHS = VecIns[Slot + 1];
12917     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12918   }
12919
12920   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12921                      VecIns.back(), VecIns.back());
12922 }
12923
12924 /// \brief return true if \c Op has a use that doesn't just read flags.
12925 static bool hasNonFlagsUse(SDValue Op) {
12926   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12927        ++UI) {
12928     SDNode *User = *UI;
12929     unsigned UOpNo = UI.getOperandNo();
12930     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12931       // Look pass truncate.
12932       UOpNo = User->use_begin().getOperandNo();
12933       User = *User->use_begin();
12934     }
12935
12936     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12937         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12938       return true;
12939   }
12940   return false;
12941 }
12942
12943 /// Emit nodes that will be selected as "test Op0,Op0", or something
12944 /// equivalent.
12945 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12946                                     SelectionDAG &DAG) const {
12947   if (Op.getValueType() == MVT::i1) {
12948     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12949     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12950                        DAG.getConstant(0, dl, MVT::i8));
12951   }
12952   // CF and OF aren't always set the way we want. Determine which
12953   // of these we need.
12954   bool NeedCF = false;
12955   bool NeedOF = false;
12956   switch (X86CC) {
12957   default: break;
12958   case X86::COND_A: case X86::COND_AE:
12959   case X86::COND_B: case X86::COND_BE:
12960     NeedCF = true;
12961     break;
12962   case X86::COND_G: case X86::COND_GE:
12963   case X86::COND_L: case X86::COND_LE:
12964   case X86::COND_O: case X86::COND_NO: {
12965     // Check if we really need to set the
12966     // Overflow flag. If NoSignedWrap is present
12967     // that is not actually needed.
12968     switch (Op->getOpcode()) {
12969     case ISD::ADD:
12970     case ISD::SUB:
12971     case ISD::MUL:
12972     case ISD::SHL: {
12973       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12974       if (BinNode->Flags.hasNoSignedWrap())
12975         break;
12976     }
12977     default:
12978       NeedOF = true;
12979       break;
12980     }
12981     break;
12982   }
12983   }
12984   // See if we can use the EFLAGS value from the operand instead of
12985   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12986   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12987   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12988     // Emit a CMP with 0, which is the TEST pattern.
12989     //if (Op.getValueType() == MVT::i1)
12990     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12991     //                     DAG.getConstant(0, MVT::i1));
12992     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12993                        DAG.getConstant(0, dl, Op.getValueType()));
12994   }
12995   unsigned Opcode = 0;
12996   unsigned NumOperands = 0;
12997
12998   // Truncate operations may prevent the merge of the SETCC instruction
12999   // and the arithmetic instruction before it. Attempt to truncate the operands
13000   // of the arithmetic instruction and use a reduced bit-width instruction.
13001   bool NeedTruncation = false;
13002   SDValue ArithOp = Op;
13003   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13004     SDValue Arith = Op->getOperand(0);
13005     // Both the trunc and the arithmetic op need to have one user each.
13006     if (Arith->hasOneUse())
13007       switch (Arith.getOpcode()) {
13008         default: break;
13009         case ISD::ADD:
13010         case ISD::SUB:
13011         case ISD::AND:
13012         case ISD::OR:
13013         case ISD::XOR: {
13014           NeedTruncation = true;
13015           ArithOp = Arith;
13016         }
13017       }
13018   }
13019
13020   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13021   // which may be the result of a CAST.  We use the variable 'Op', which is the
13022   // non-casted variable when we check for possible users.
13023   switch (ArithOp.getOpcode()) {
13024   case ISD::ADD:
13025     // Due to an isel shortcoming, be conservative if this add is likely to be
13026     // selected as part of a load-modify-store instruction. When the root node
13027     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13028     // uses of other nodes in the match, such as the ADD in this case. This
13029     // leads to the ADD being left around and reselected, with the result being
13030     // two adds in the output.  Alas, even if none our users are stores, that
13031     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13032     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13033     // climbing the DAG back to the root, and it doesn't seem to be worth the
13034     // effort.
13035     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13036          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13037       if (UI->getOpcode() != ISD::CopyToReg &&
13038           UI->getOpcode() != ISD::SETCC &&
13039           UI->getOpcode() != ISD::STORE)
13040         goto default_case;
13041
13042     if (ConstantSDNode *C =
13043         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13044       // An add of one will be selected as an INC.
13045       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13046         Opcode = X86ISD::INC;
13047         NumOperands = 1;
13048         break;
13049       }
13050
13051       // An add of negative one (subtract of one) will be selected as a DEC.
13052       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13053         Opcode = X86ISD::DEC;
13054         NumOperands = 1;
13055         break;
13056       }
13057     }
13058
13059     // Otherwise use a regular EFLAGS-setting add.
13060     Opcode = X86ISD::ADD;
13061     NumOperands = 2;
13062     break;
13063   case ISD::SHL:
13064   case ISD::SRL:
13065     // If we have a constant logical shift that's only used in a comparison
13066     // against zero turn it into an equivalent AND. This allows turning it into
13067     // a TEST instruction later.
13068     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13069         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13070       EVT VT = Op.getValueType();
13071       unsigned BitWidth = VT.getSizeInBits();
13072       unsigned ShAmt = Op->getConstantOperandVal(1);
13073       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13074         break;
13075       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13076                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13077                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13078       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13079         break;
13080       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13081                                 DAG.getConstant(Mask, dl, VT));
13082       DAG.ReplaceAllUsesWith(Op, New);
13083       Op = New;
13084     }
13085     break;
13086
13087   case ISD::AND:
13088     // If the primary and result isn't used, don't bother using X86ISD::AND,
13089     // because a TEST instruction will be better.
13090     if (!hasNonFlagsUse(Op))
13091       break;
13092     // FALL THROUGH
13093   case ISD::SUB:
13094   case ISD::OR:
13095   case ISD::XOR:
13096     // Due to the ISEL shortcoming noted above, be conservative if this op is
13097     // likely to be selected as part of a load-modify-store instruction.
13098     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13099            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13100       if (UI->getOpcode() == ISD::STORE)
13101         goto default_case;
13102
13103     // Otherwise use a regular EFLAGS-setting instruction.
13104     switch (ArithOp.getOpcode()) {
13105     default: llvm_unreachable("unexpected operator!");
13106     case ISD::SUB: Opcode = X86ISD::SUB; break;
13107     case ISD::XOR: Opcode = X86ISD::XOR; break;
13108     case ISD::AND: Opcode = X86ISD::AND; break;
13109     case ISD::OR: {
13110       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13111         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13112         if (EFLAGS.getNode())
13113           return EFLAGS;
13114       }
13115       Opcode = X86ISD::OR;
13116       break;
13117     }
13118     }
13119
13120     NumOperands = 2;
13121     break;
13122   case X86ISD::ADD:
13123   case X86ISD::SUB:
13124   case X86ISD::INC:
13125   case X86ISD::DEC:
13126   case X86ISD::OR:
13127   case X86ISD::XOR:
13128   case X86ISD::AND:
13129     return SDValue(Op.getNode(), 1);
13130   default:
13131   default_case:
13132     break;
13133   }
13134
13135   // If we found that truncation is beneficial, perform the truncation and
13136   // update 'Op'.
13137   if (NeedTruncation) {
13138     EVT VT = Op.getValueType();
13139     SDValue WideVal = Op->getOperand(0);
13140     EVT WideVT = WideVal.getValueType();
13141     unsigned ConvertedOp = 0;
13142     // Use a target machine opcode to prevent further DAGCombine
13143     // optimizations that may separate the arithmetic operations
13144     // from the setcc node.
13145     switch (WideVal.getOpcode()) {
13146       default: break;
13147       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13148       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13149       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13150       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13151       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13152     }
13153
13154     if (ConvertedOp) {
13155       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13156       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13157         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13158         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13159         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13160       }
13161     }
13162   }
13163
13164   if (Opcode == 0)
13165     // Emit a CMP with 0, which is the TEST pattern.
13166     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13167                        DAG.getConstant(0, dl, Op.getValueType()));
13168
13169   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13170   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13171
13172   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13173   DAG.ReplaceAllUsesWith(Op, New);
13174   return SDValue(New.getNode(), 1);
13175 }
13176
13177 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13178 /// equivalent.
13179 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13180                                    SDLoc dl, SelectionDAG &DAG) const {
13181   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13182     if (C->getAPIntValue() == 0)
13183       return EmitTest(Op0, X86CC, dl, DAG);
13184
13185      if (Op0.getValueType() == MVT::i1)
13186        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13187   }
13188
13189   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13190        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13191     // Do the comparison at i32 if it's smaller, besides the Atom case.
13192     // This avoids subregister aliasing issues. Keep the smaller reference
13193     // if we're optimizing for size, however, as that'll allow better folding
13194     // of memory operations.
13195     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13196         !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13197         !Subtarget->isAtom()) {
13198       unsigned ExtendOp =
13199           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13200       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13201       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13202     }
13203     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13204     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13205     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13206                               Op0, Op1);
13207     return SDValue(Sub.getNode(), 1);
13208   }
13209   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13210 }
13211
13212 /// Convert a comparison if required by the subtarget.
13213 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13214                                                  SelectionDAG &DAG) const {
13215   // If the subtarget does not support the FUCOMI instruction, floating-point
13216   // comparisons have to be converted.
13217   if (Subtarget->hasCMov() ||
13218       Cmp.getOpcode() != X86ISD::CMP ||
13219       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13220       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13221     return Cmp;
13222
13223   // The instruction selector will select an FUCOM instruction instead of
13224   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13225   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13226   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13227   SDLoc dl(Cmp);
13228   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13229   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13230   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13231                             DAG.getConstant(8, dl, MVT::i8));
13232   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13233   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13234 }
13235
13236 /// The minimum architected relative accuracy is 2^-12. We need one
13237 /// Newton-Raphson step to have a good float result (24 bits of precision).
13238 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13239                                             DAGCombinerInfo &DCI,
13240                                             unsigned &RefinementSteps,
13241                                             bool &UseOneConstNR) const {
13242   EVT VT = Op.getValueType();
13243   const char *RecipOp;
13244
13245   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13246   // TODO: Add support for AVX512 (v16f32).
13247   // It is likely not profitable to do this for f64 because a double-precision
13248   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13249   // instructions: convert to single, rsqrtss, convert back to double, refine
13250   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13251   // along with FMA, this could be a throughput win.
13252   if (VT == MVT::f32 && Subtarget->hasSSE1())
13253     RecipOp = "sqrtf";
13254   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13255            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13256     RecipOp = "vec-sqrtf";
13257   else
13258     return SDValue();
13259
13260   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13261   if (!Recips.isEnabled(RecipOp))
13262     return SDValue();
13263
13264   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13265   UseOneConstNR = false;
13266   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13267 }
13268
13269 /// The minimum architected relative accuracy is 2^-12. We need one
13270 /// Newton-Raphson step to have a good float result (24 bits of precision).
13271 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13272                                             DAGCombinerInfo &DCI,
13273                                             unsigned &RefinementSteps) const {
13274   EVT VT = Op.getValueType();
13275   const char *RecipOp;
13276
13277   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13278   // TODO: Add support for AVX512 (v16f32).
13279   // It is likely not profitable to do this for f64 because a double-precision
13280   // reciprocal estimate with refinement on x86 prior to FMA requires
13281   // 15 instructions: convert to single, rcpss, convert back to double, refine
13282   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13283   // along with FMA, this could be a throughput win.
13284   if (VT == MVT::f32 && Subtarget->hasSSE1())
13285     RecipOp = "divf";
13286   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13287            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13288     RecipOp = "vec-divf";
13289   else
13290     return SDValue();
13291
13292   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13293   if (!Recips.isEnabled(RecipOp))
13294     return SDValue();
13295
13296   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13297   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13298 }
13299
13300 /// If we have at least two divisions that use the same divisor, convert to
13301 /// multplication by a reciprocal. This may need to be adjusted for a given
13302 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13303 /// This is because we still need one division to calculate the reciprocal and
13304 /// then we need two multiplies by that reciprocal as replacements for the
13305 /// original divisions.
13306 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13307   return 2;
13308 }
13309
13310 static bool isAllOnes(SDValue V) {
13311   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13312   return C && C->isAllOnesValue();
13313 }
13314
13315 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13316 /// if it's possible.
13317 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13318                                      SDLoc dl, SelectionDAG &DAG) const {
13319   SDValue Op0 = And.getOperand(0);
13320   SDValue Op1 = And.getOperand(1);
13321   if (Op0.getOpcode() == ISD::TRUNCATE)
13322     Op0 = Op0.getOperand(0);
13323   if (Op1.getOpcode() == ISD::TRUNCATE)
13324     Op1 = Op1.getOperand(0);
13325
13326   SDValue LHS, RHS;
13327   if (Op1.getOpcode() == ISD::SHL)
13328     std::swap(Op0, Op1);
13329   if (Op0.getOpcode() == ISD::SHL) {
13330     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13331       if (And00C->getZExtValue() == 1) {
13332         // If we looked past a truncate, check that it's only truncating away
13333         // known zeros.
13334         unsigned BitWidth = Op0.getValueSizeInBits();
13335         unsigned AndBitWidth = And.getValueSizeInBits();
13336         if (BitWidth > AndBitWidth) {
13337           APInt Zeros, Ones;
13338           DAG.computeKnownBits(Op0, Zeros, Ones);
13339           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13340             return SDValue();
13341         }
13342         LHS = Op1;
13343         RHS = Op0.getOperand(1);
13344       }
13345   } else if (Op1.getOpcode() == ISD::Constant) {
13346     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13347     uint64_t AndRHSVal = AndRHS->getZExtValue();
13348     SDValue AndLHS = Op0;
13349
13350     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13351       LHS = AndLHS.getOperand(0);
13352       RHS = AndLHS.getOperand(1);
13353     }
13354
13355     // Use BT if the immediate can't be encoded in a TEST instruction.
13356     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13357       LHS = AndLHS;
13358       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13359     }
13360   }
13361
13362   if (LHS.getNode()) {
13363     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13364     // instruction.  Since the shift amount is in-range-or-undefined, we know
13365     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13366     // the encoding for the i16 version is larger than the i32 version.
13367     // Also promote i16 to i32 for performance / code size reason.
13368     if (LHS.getValueType() == MVT::i8 ||
13369         LHS.getValueType() == MVT::i16)
13370       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13371
13372     // If the operand types disagree, extend the shift amount to match.  Since
13373     // BT ignores high bits (like shifts) we can use anyextend.
13374     if (LHS.getValueType() != RHS.getValueType())
13375       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13376
13377     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13378     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13379     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13380                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13381   }
13382
13383   return SDValue();
13384 }
13385
13386 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13387 /// mask CMPs.
13388 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13389                               SDValue &Op1) {
13390   unsigned SSECC;
13391   bool Swap = false;
13392
13393   // SSE Condition code mapping:
13394   //  0 - EQ
13395   //  1 - LT
13396   //  2 - LE
13397   //  3 - UNORD
13398   //  4 - NEQ
13399   //  5 - NLT
13400   //  6 - NLE
13401   //  7 - ORD
13402   switch (SetCCOpcode) {
13403   default: llvm_unreachable("Unexpected SETCC condition");
13404   case ISD::SETOEQ:
13405   case ISD::SETEQ:  SSECC = 0; break;
13406   case ISD::SETOGT:
13407   case ISD::SETGT:  Swap = true; // Fallthrough
13408   case ISD::SETLT:
13409   case ISD::SETOLT: SSECC = 1; break;
13410   case ISD::SETOGE:
13411   case ISD::SETGE:  Swap = true; // Fallthrough
13412   case ISD::SETLE:
13413   case ISD::SETOLE: SSECC = 2; break;
13414   case ISD::SETUO:  SSECC = 3; break;
13415   case ISD::SETUNE:
13416   case ISD::SETNE:  SSECC = 4; break;
13417   case ISD::SETULE: Swap = true; // Fallthrough
13418   case ISD::SETUGE: SSECC = 5; break;
13419   case ISD::SETULT: Swap = true; // Fallthrough
13420   case ISD::SETUGT: SSECC = 6; break;
13421   case ISD::SETO:   SSECC = 7; break;
13422   case ISD::SETUEQ:
13423   case ISD::SETONE: SSECC = 8; break;
13424   }
13425   if (Swap)
13426     std::swap(Op0, Op1);
13427
13428   return SSECC;
13429 }
13430
13431 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13432 // ones, and then concatenate the result back.
13433 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13434   MVT VT = Op.getSimpleValueType();
13435
13436   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13437          "Unsupported value type for operation");
13438
13439   unsigned NumElems = VT.getVectorNumElements();
13440   SDLoc dl(Op);
13441   SDValue CC = Op.getOperand(2);
13442
13443   // Extract the LHS vectors
13444   SDValue LHS = Op.getOperand(0);
13445   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13446   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13447
13448   // Extract the RHS vectors
13449   SDValue RHS = Op.getOperand(1);
13450   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13451   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13452
13453   // Issue the operation on the smaller types and concatenate the result back
13454   MVT EltVT = VT.getVectorElementType();
13455   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13456   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13457                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13458                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13459 }
13460
13461 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13462   SDValue Op0 = Op.getOperand(0);
13463   SDValue Op1 = Op.getOperand(1);
13464   SDValue CC = Op.getOperand(2);
13465   MVT VT = Op.getSimpleValueType();
13466   SDLoc dl(Op);
13467
13468   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13469          "Unexpected type for boolean compare operation");
13470   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13471   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13472                                DAG.getConstant(-1, dl, VT));
13473   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13474                                DAG.getConstant(-1, dl, VT));
13475   switch (SetCCOpcode) {
13476   default: llvm_unreachable("Unexpected SETCC condition");
13477   case ISD::SETEQ:
13478     // (x == y) -> ~(x ^ y)
13479     return DAG.getNode(ISD::XOR, dl, VT,
13480                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13481                        DAG.getConstant(-1, dl, VT));
13482   case ISD::SETNE:
13483     // (x != y) -> (x ^ y)
13484     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13485   case ISD::SETUGT:
13486   case ISD::SETGT:
13487     // (x > y) -> (x & ~y)
13488     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13489   case ISD::SETULT:
13490   case ISD::SETLT:
13491     // (x < y) -> (~x & y)
13492     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13493   case ISD::SETULE:
13494   case ISD::SETLE:
13495     // (x <= y) -> (~x | y)
13496     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13497   case ISD::SETUGE:
13498   case ISD::SETGE:
13499     // (x >=y) -> (x | ~y)
13500     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13501   }
13502 }
13503
13504 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13505                                      const X86Subtarget *Subtarget) {
13506   SDValue Op0 = Op.getOperand(0);
13507   SDValue Op1 = Op.getOperand(1);
13508   SDValue CC = Op.getOperand(2);
13509   MVT VT = Op.getSimpleValueType();
13510   SDLoc dl(Op);
13511
13512   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13513          Op.getValueType().getScalarType() == MVT::i1 &&
13514          "Cannot set masked compare for this operation");
13515
13516   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13517   unsigned  Opc = 0;
13518   bool Unsigned = false;
13519   bool Swap = false;
13520   unsigned SSECC;
13521   switch (SetCCOpcode) {
13522   default: llvm_unreachable("Unexpected SETCC condition");
13523   case ISD::SETNE:  SSECC = 4; break;
13524   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13525   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13526   case ISD::SETLT:  Swap = true; //fall-through
13527   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13528   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13529   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13530   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13531   case ISD::SETULE: Unsigned = true; //fall-through
13532   case ISD::SETLE:  SSECC = 2; break;
13533   }
13534
13535   if (Swap)
13536     std::swap(Op0, Op1);
13537   if (Opc)
13538     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13539   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13540   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13541                      DAG.getConstant(SSECC, dl, MVT::i8));
13542 }
13543
13544 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13545 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13546 /// return an empty value.
13547 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13548 {
13549   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13550   if (!BV)
13551     return SDValue();
13552
13553   MVT VT = Op1.getSimpleValueType();
13554   MVT EVT = VT.getVectorElementType();
13555   unsigned n = VT.getVectorNumElements();
13556   SmallVector<SDValue, 8> ULTOp1;
13557
13558   for (unsigned i = 0; i < n; ++i) {
13559     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13560     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13561       return SDValue();
13562
13563     // Avoid underflow.
13564     APInt Val = Elt->getAPIntValue();
13565     if (Val == 0)
13566       return SDValue();
13567
13568     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13569   }
13570
13571   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13572 }
13573
13574 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13575                            SelectionDAG &DAG) {
13576   SDValue Op0 = Op.getOperand(0);
13577   SDValue Op1 = Op.getOperand(1);
13578   SDValue CC = Op.getOperand(2);
13579   MVT VT = Op.getSimpleValueType();
13580   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13581   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13582   SDLoc dl(Op);
13583
13584   if (isFP) {
13585 #ifndef NDEBUG
13586     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13587     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13588 #endif
13589
13590     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13591     unsigned Opc = X86ISD::CMPP;
13592     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13593       assert(VT.getVectorNumElements() <= 16);
13594       Opc = X86ISD::CMPM;
13595     }
13596     // In the two special cases we can't handle, emit two comparisons.
13597     if (SSECC == 8) {
13598       unsigned CC0, CC1;
13599       unsigned CombineOpc;
13600       if (SetCCOpcode == ISD::SETUEQ) {
13601         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13602       } else {
13603         assert(SetCCOpcode == ISD::SETONE);
13604         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13605       }
13606
13607       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13608                                  DAG.getConstant(CC0, dl, MVT::i8));
13609       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13610                                  DAG.getConstant(CC1, dl, MVT::i8));
13611       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13612     }
13613     // Handle all other FP comparisons here.
13614     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13615                        DAG.getConstant(SSECC, dl, MVT::i8));
13616   }
13617
13618   // Break 256-bit integer vector compare into smaller ones.
13619   if (VT.is256BitVector() && !Subtarget->hasInt256())
13620     return Lower256IntVSETCC(Op, DAG);
13621
13622   EVT OpVT = Op1.getValueType();
13623   if (OpVT.getVectorElementType() == MVT::i1)
13624     return LowerBoolVSETCC_AVX512(Op, DAG);
13625
13626   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13627   if (Subtarget->hasAVX512()) {
13628     if (Op1.getValueType().is512BitVector() ||
13629         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13630         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13631       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13632
13633     // In AVX-512 architecture setcc returns mask with i1 elements,
13634     // But there is no compare instruction for i8 and i16 elements in KNL.
13635     // We are not talking about 512-bit operands in this case, these
13636     // types are illegal.
13637     if (MaskResult &&
13638         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13639          OpVT.getVectorElementType().getSizeInBits() >= 8))
13640       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13641                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13642   }
13643
13644   // We are handling one of the integer comparisons here.  Since SSE only has
13645   // GT and EQ comparisons for integer, swapping operands and multiple
13646   // operations may be required for some comparisons.
13647   unsigned Opc;
13648   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13649   bool Subus = false;
13650
13651   switch (SetCCOpcode) {
13652   default: llvm_unreachable("Unexpected SETCC condition");
13653   case ISD::SETNE:  Invert = true;
13654   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13655   case ISD::SETLT:  Swap = true;
13656   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13657   case ISD::SETGE:  Swap = true;
13658   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13659                     Invert = true; break;
13660   case ISD::SETULT: Swap = true;
13661   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13662                     FlipSigns = true; break;
13663   case ISD::SETUGE: Swap = true;
13664   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13665                     FlipSigns = true; Invert = true; break;
13666   }
13667
13668   // Special case: Use min/max operations for SETULE/SETUGE
13669   MVT VET = VT.getVectorElementType();
13670   bool hasMinMax =
13671        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13672     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13673
13674   if (hasMinMax) {
13675     switch (SetCCOpcode) {
13676     default: break;
13677     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13678     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13679     }
13680
13681     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13682   }
13683
13684   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13685   if (!MinMax && hasSubus) {
13686     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13687     // Op0 u<= Op1:
13688     //   t = psubus Op0, Op1
13689     //   pcmpeq t, <0..0>
13690     switch (SetCCOpcode) {
13691     default: break;
13692     case ISD::SETULT: {
13693       // If the comparison is against a constant we can turn this into a
13694       // setule.  With psubus, setule does not require a swap.  This is
13695       // beneficial because the constant in the register is no longer
13696       // destructed as the destination so it can be hoisted out of a loop.
13697       // Only do this pre-AVX since vpcmp* is no longer destructive.
13698       if (Subtarget->hasAVX())
13699         break;
13700       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13701       if (ULEOp1.getNode()) {
13702         Op1 = ULEOp1;
13703         Subus = true; Invert = false; Swap = false;
13704       }
13705       break;
13706     }
13707     // Psubus is better than flip-sign because it requires no inversion.
13708     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13709     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13710     }
13711
13712     if (Subus) {
13713       Opc = X86ISD::SUBUS;
13714       FlipSigns = false;
13715     }
13716   }
13717
13718   if (Swap)
13719     std::swap(Op0, Op1);
13720
13721   // Check that the operation in question is available (most are plain SSE2,
13722   // but PCMPGTQ and PCMPEQQ have different requirements).
13723   if (VT == MVT::v2i64) {
13724     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13725       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13726
13727       // First cast everything to the right type.
13728       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13729       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13730
13731       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13732       // bits of the inputs before performing those operations. The lower
13733       // compare is always unsigned.
13734       SDValue SB;
13735       if (FlipSigns) {
13736         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13737       } else {
13738         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13739         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13740         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13741                          Sign, Zero, Sign, Zero);
13742       }
13743       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13744       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13745
13746       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13747       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13748       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13749
13750       // Create masks for only the low parts/high parts of the 64 bit integers.
13751       static const int MaskHi[] = { 1, 1, 3, 3 };
13752       static const int MaskLo[] = { 0, 0, 2, 2 };
13753       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13754       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13755       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13756
13757       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13758       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13759
13760       if (Invert)
13761         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13762
13763       return DAG.getBitcast(VT, Result);
13764     }
13765
13766     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13767       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13768       // pcmpeqd + pshufd + pand.
13769       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13770
13771       // First cast everything to the right type.
13772       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13773       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13774
13775       // Do the compare.
13776       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13777
13778       // Make sure the lower and upper halves are both all-ones.
13779       static const int Mask[] = { 1, 0, 3, 2 };
13780       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13781       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13782
13783       if (Invert)
13784         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13785
13786       return DAG.getBitcast(VT, Result);
13787     }
13788   }
13789
13790   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13791   // bits of the inputs before performing those operations.
13792   if (FlipSigns) {
13793     EVT EltVT = VT.getVectorElementType();
13794     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13795                                  VT);
13796     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13797     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13798   }
13799
13800   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13801
13802   // If the logical-not of the result is required, perform that now.
13803   if (Invert)
13804     Result = DAG.getNOT(dl, Result, VT);
13805
13806   if (MinMax)
13807     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13808
13809   if (Subus)
13810     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13811                          getZeroVector(VT, Subtarget, DAG, dl));
13812
13813   return Result;
13814 }
13815
13816 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13817
13818   MVT VT = Op.getSimpleValueType();
13819
13820   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13821
13822   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13823          && "SetCC type must be 8-bit or 1-bit integer");
13824   SDValue Op0 = Op.getOperand(0);
13825   SDValue Op1 = Op.getOperand(1);
13826   SDLoc dl(Op);
13827   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13828
13829   // Optimize to BT if possible.
13830   // Lower (X & (1 << N)) == 0 to BT(X, N).
13831   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13832   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13833   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13834       Op1.getOpcode() == ISD::Constant &&
13835       cast<ConstantSDNode>(Op1)->isNullValue() &&
13836       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13837     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13838     if (NewSetCC.getNode()) {
13839       if (VT == MVT::i1)
13840         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13841       return NewSetCC;
13842     }
13843   }
13844
13845   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13846   // these.
13847   if (Op1.getOpcode() == ISD::Constant &&
13848       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13849        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13850       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13851
13852     // If the input is a setcc, then reuse the input setcc or use a new one with
13853     // the inverted condition.
13854     if (Op0.getOpcode() == X86ISD::SETCC) {
13855       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13856       bool Invert = (CC == ISD::SETNE) ^
13857         cast<ConstantSDNode>(Op1)->isNullValue();
13858       if (!Invert)
13859         return Op0;
13860
13861       CCode = X86::GetOppositeBranchCondition(CCode);
13862       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13863                                   DAG.getConstant(CCode, dl, MVT::i8),
13864                                   Op0.getOperand(1));
13865       if (VT == MVT::i1)
13866         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13867       return SetCC;
13868     }
13869   }
13870   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13871       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13872       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13873
13874     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13875     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13876   }
13877
13878   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13879   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13880   if (X86CC == X86::COND_INVALID)
13881     return SDValue();
13882
13883   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13884   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13885   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13886                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13887   if (VT == MVT::i1)
13888     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13889   return SetCC;
13890 }
13891
13892 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13893 static bool isX86LogicalCmp(SDValue Op) {
13894   unsigned Opc = Op.getNode()->getOpcode();
13895   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13896       Opc == X86ISD::SAHF)
13897     return true;
13898   if (Op.getResNo() == 1 &&
13899       (Opc == X86ISD::ADD ||
13900        Opc == X86ISD::SUB ||
13901        Opc == X86ISD::ADC ||
13902        Opc == X86ISD::SBB ||
13903        Opc == X86ISD::SMUL ||
13904        Opc == X86ISD::UMUL ||
13905        Opc == X86ISD::INC ||
13906        Opc == X86ISD::DEC ||
13907        Opc == X86ISD::OR ||
13908        Opc == X86ISD::XOR ||
13909        Opc == X86ISD::AND))
13910     return true;
13911
13912   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13913     return true;
13914
13915   return false;
13916 }
13917
13918 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13919   if (V.getOpcode() != ISD::TRUNCATE)
13920     return false;
13921
13922   SDValue VOp0 = V.getOperand(0);
13923   unsigned InBits = VOp0.getValueSizeInBits();
13924   unsigned Bits = V.getValueSizeInBits();
13925   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13926 }
13927
13928 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13929   bool addTest = true;
13930   SDValue Cond  = Op.getOperand(0);
13931   SDValue Op1 = Op.getOperand(1);
13932   SDValue Op2 = Op.getOperand(2);
13933   SDLoc DL(Op);
13934   EVT VT = Op1.getValueType();
13935   SDValue CC;
13936
13937   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13938   // are available or VBLENDV if AVX is available.
13939   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13940   if (Cond.getOpcode() == ISD::SETCC &&
13941       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13942        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13943       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13944     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13945     int SSECC = translateX86FSETCC(
13946         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13947
13948     if (SSECC != 8) {
13949       if (Subtarget->hasAVX512()) {
13950         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13951                                   DAG.getConstant(SSECC, DL, MVT::i8));
13952         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13953       }
13954
13955       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13956                                 DAG.getConstant(SSECC, DL, MVT::i8));
13957
13958       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13959       // of 3 logic instructions for size savings and potentially speed.
13960       // Unfortunately, there is no scalar form of VBLENDV.
13961
13962       // If either operand is a constant, don't try this. We can expect to
13963       // optimize away at least one of the logic instructions later in that
13964       // case, so that sequence would be faster than a variable blend.
13965
13966       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13967       // uses XMM0 as the selection register. That may need just as many
13968       // instructions as the AND/ANDN/OR sequence due to register moves, so
13969       // don't bother.
13970
13971       if (Subtarget->hasAVX() &&
13972           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13973
13974         // Convert to vectors, do a VSELECT, and convert back to scalar.
13975         // All of the conversions should be optimized away.
13976
13977         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13978         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13979         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13980         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13981
13982         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13983         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13984
13985         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13986
13987         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13988                            VSel, DAG.getIntPtrConstant(0, DL));
13989       }
13990       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13991       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13992       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13993     }
13994   }
13995
13996   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13997     SDValue Op1Scalar;
13998     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13999       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14000     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14001       Op1Scalar = Op1.getOperand(0);
14002     SDValue Op2Scalar;
14003     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14004       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14005     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14006       Op2Scalar = Op2.getOperand(0);
14007     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14008       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14009                                       Op1Scalar.getValueType(),
14010                                       Cond, Op1Scalar, Op2Scalar);
14011       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14012         return DAG.getBitcast(VT, newSelect);
14013       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14014       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14015                          DAG.getIntPtrConstant(0, DL));
14016     }
14017   }
14018
14019   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14020     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14021     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14022                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14023     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14024                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14025     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14026                                     Cond, Op1, Op2);
14027     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14028   }
14029
14030   if (Cond.getOpcode() == ISD::SETCC) {
14031     SDValue NewCond = LowerSETCC(Cond, DAG);
14032     if (NewCond.getNode())
14033       Cond = NewCond;
14034   }
14035
14036   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14037   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14038   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14039   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14040   if (Cond.getOpcode() == X86ISD::SETCC &&
14041       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14042       isZero(Cond.getOperand(1).getOperand(1))) {
14043     SDValue Cmp = Cond.getOperand(1);
14044
14045     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14046
14047     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14048         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14049       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14050
14051       SDValue CmpOp0 = Cmp.getOperand(0);
14052       // Apply further optimizations for special cases
14053       // (select (x != 0), -1, 0) -> neg & sbb
14054       // (select (x == 0), 0, -1) -> neg & sbb
14055       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14056         if (YC->isNullValue() &&
14057             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14058           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14059           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14060                                     DAG.getConstant(0, DL,
14061                                                     CmpOp0.getValueType()),
14062                                     CmpOp0);
14063           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14064                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14065                                     SDValue(Neg.getNode(), 1));
14066           return Res;
14067         }
14068
14069       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14070                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14071       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14072
14073       SDValue Res =   // Res = 0 or -1.
14074         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14075                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14076
14077       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14078         Res = DAG.getNOT(DL, Res, Res.getValueType());
14079
14080       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14081       if (!N2C || !N2C->isNullValue())
14082         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14083       return Res;
14084     }
14085   }
14086
14087   // Look past (and (setcc_carry (cmp ...)), 1).
14088   if (Cond.getOpcode() == ISD::AND &&
14089       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14090     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14091     if (C && C->getAPIntValue() == 1)
14092       Cond = Cond.getOperand(0);
14093   }
14094
14095   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14096   // setting operand in place of the X86ISD::SETCC.
14097   unsigned CondOpcode = Cond.getOpcode();
14098   if (CondOpcode == X86ISD::SETCC ||
14099       CondOpcode == X86ISD::SETCC_CARRY) {
14100     CC = Cond.getOperand(0);
14101
14102     SDValue Cmp = Cond.getOperand(1);
14103     unsigned Opc = Cmp.getOpcode();
14104     MVT VT = Op.getSimpleValueType();
14105
14106     bool IllegalFPCMov = false;
14107     if (VT.isFloatingPoint() && !VT.isVector() &&
14108         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14109       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14110
14111     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14112         Opc == X86ISD::BT) { // FIXME
14113       Cond = Cmp;
14114       addTest = false;
14115     }
14116   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14117              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14118              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14119               Cond.getOperand(0).getValueType() != MVT::i8)) {
14120     SDValue LHS = Cond.getOperand(0);
14121     SDValue RHS = Cond.getOperand(1);
14122     unsigned X86Opcode;
14123     unsigned X86Cond;
14124     SDVTList VTs;
14125     switch (CondOpcode) {
14126     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14127     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14128     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14129     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14130     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14131     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14132     default: llvm_unreachable("unexpected overflowing operator");
14133     }
14134     if (CondOpcode == ISD::UMULO)
14135       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14136                           MVT::i32);
14137     else
14138       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14139
14140     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14141
14142     if (CondOpcode == ISD::UMULO)
14143       Cond = X86Op.getValue(2);
14144     else
14145       Cond = X86Op.getValue(1);
14146
14147     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14148     addTest = false;
14149   }
14150
14151   if (addTest) {
14152     // Look past the truncate if the high bits are known zero.
14153     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14154       Cond = Cond.getOperand(0);
14155
14156     // We know the result of AND is compared against zero. Try to match
14157     // it to BT.
14158     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14159       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14160       if (NewSetCC.getNode()) {
14161         CC = NewSetCC.getOperand(0);
14162         Cond = NewSetCC.getOperand(1);
14163         addTest = false;
14164       }
14165     }
14166   }
14167
14168   if (addTest) {
14169     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14170     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14171   }
14172
14173   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14174   // a <  b ?  0 : -1 -> RES = setcc_carry
14175   // a >= b ? -1 :  0 -> RES = setcc_carry
14176   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14177   if (Cond.getOpcode() == X86ISD::SUB) {
14178     Cond = ConvertCmpIfNecessary(Cond, DAG);
14179     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14180
14181     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14182         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14183       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14184                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14185                                 Cond);
14186       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14187         return DAG.getNOT(DL, Res, Res.getValueType());
14188       return Res;
14189     }
14190   }
14191
14192   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14193   // widen the cmov and push the truncate through. This avoids introducing a new
14194   // branch during isel and doesn't add any extensions.
14195   if (Op.getValueType() == MVT::i8 &&
14196       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14197     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14198     if (T1.getValueType() == T2.getValueType() &&
14199         // Blacklist CopyFromReg to avoid partial register stalls.
14200         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14201       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14202       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14203       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14204     }
14205   }
14206
14207   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14208   // condition is true.
14209   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14210   SDValue Ops[] = { Op2, Op1, CC, Cond };
14211   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14212 }
14213
14214 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14215                                        const X86Subtarget *Subtarget,
14216                                        SelectionDAG &DAG) {
14217   MVT VT = Op->getSimpleValueType(0);
14218   SDValue In = Op->getOperand(0);
14219   MVT InVT = In.getSimpleValueType();
14220   MVT VTElt = VT.getVectorElementType();
14221   MVT InVTElt = InVT.getVectorElementType();
14222   SDLoc dl(Op);
14223
14224   // SKX processor
14225   if ((InVTElt == MVT::i1) &&
14226       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14227         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14228
14229        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14230         VTElt.getSizeInBits() <= 16)) ||
14231
14232        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14233         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14234
14235        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14236         VTElt.getSizeInBits() >= 32))))
14237     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14238
14239   unsigned int NumElts = VT.getVectorNumElements();
14240
14241   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14242     return SDValue();
14243
14244   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14245     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14246       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14247     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14248   }
14249
14250   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14251   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14252   SDValue NegOne =
14253    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14254                    ExtVT);
14255   SDValue Zero =
14256    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14257
14258   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14259   if (VT.is512BitVector())
14260     return V;
14261   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14262 }
14263
14264 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14265                                              const X86Subtarget *Subtarget,
14266                                              SelectionDAG &DAG) {
14267   SDValue In = Op->getOperand(0);
14268   MVT VT = Op->getSimpleValueType(0);
14269   MVT InVT = In.getSimpleValueType();
14270   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14271
14272   MVT InSVT = InVT.getScalarType();
14273   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14274
14275   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14276     return SDValue();
14277   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14278     return SDValue();
14279
14280   SDLoc dl(Op);
14281
14282   // SSE41 targets can use the pmovsx* instructions directly.
14283   if (Subtarget->hasSSE41())
14284     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14285
14286   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14287   SDValue Curr = In;
14288   MVT CurrVT = InVT;
14289
14290   // As SRAI is only available on i16/i32 types, we expand only up to i32
14291   // and handle i64 separately.
14292   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14293     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14294     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14295     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14296     Curr = DAG.getBitcast(CurrVT, Curr);
14297   }
14298
14299   SDValue SignExt = Curr;
14300   if (CurrVT != InVT) {
14301     unsigned SignExtShift =
14302         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14303     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14304                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14305   }
14306
14307   if (CurrVT == VT)
14308     return SignExt;
14309
14310   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14311     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14312                                DAG.getConstant(31, dl, MVT::i8));
14313     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14314     return DAG.getBitcast(VT, Ext);
14315   }
14316
14317   return SDValue();
14318 }
14319
14320 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14321                                 SelectionDAG &DAG) {
14322   MVT VT = Op->getSimpleValueType(0);
14323   SDValue In = Op->getOperand(0);
14324   MVT InVT = In.getSimpleValueType();
14325   SDLoc dl(Op);
14326
14327   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14328     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14329
14330   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14331       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14332       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14333     return SDValue();
14334
14335   if (Subtarget->hasInt256())
14336     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14337
14338   // Optimize vectors in AVX mode
14339   // Sign extend  v8i16 to v8i32 and
14340   //              v4i32 to v4i64
14341   //
14342   // Divide input vector into two parts
14343   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14344   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14345   // concat the vectors to original VT
14346
14347   unsigned NumElems = InVT.getVectorNumElements();
14348   SDValue Undef = DAG.getUNDEF(InVT);
14349
14350   SmallVector<int,8> ShufMask1(NumElems, -1);
14351   for (unsigned i = 0; i != NumElems/2; ++i)
14352     ShufMask1[i] = i;
14353
14354   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14355
14356   SmallVector<int,8> ShufMask2(NumElems, -1);
14357   for (unsigned i = 0; i != NumElems/2; ++i)
14358     ShufMask2[i] = i + NumElems/2;
14359
14360   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14361
14362   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14363                                 VT.getVectorNumElements()/2);
14364
14365   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14366   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14367
14368   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14369 }
14370
14371 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14372 // may emit an illegal shuffle but the expansion is still better than scalar
14373 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14374 // we'll emit a shuffle and a arithmetic shift.
14375 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14376 // TODO: It is possible to support ZExt by zeroing the undef values during
14377 // the shuffle phase or after the shuffle.
14378 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14379                                  SelectionDAG &DAG) {
14380   MVT RegVT = Op.getSimpleValueType();
14381   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14382   assert(RegVT.isInteger() &&
14383          "We only custom lower integer vector sext loads.");
14384
14385   // Nothing useful we can do without SSE2 shuffles.
14386   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14387
14388   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14389   SDLoc dl(Ld);
14390   EVT MemVT = Ld->getMemoryVT();
14391   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14392   unsigned RegSz = RegVT.getSizeInBits();
14393
14394   ISD::LoadExtType Ext = Ld->getExtensionType();
14395
14396   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14397          && "Only anyext and sext are currently implemented.");
14398   assert(MemVT != RegVT && "Cannot extend to the same type");
14399   assert(MemVT.isVector() && "Must load a vector from memory");
14400
14401   unsigned NumElems = RegVT.getVectorNumElements();
14402   unsigned MemSz = MemVT.getSizeInBits();
14403   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14404
14405   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14406     // The only way in which we have a legal 256-bit vector result but not the
14407     // integer 256-bit operations needed to directly lower a sextload is if we
14408     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14409     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14410     // correctly legalized. We do this late to allow the canonical form of
14411     // sextload to persist throughout the rest of the DAG combiner -- it wants
14412     // to fold together any extensions it can, and so will fuse a sign_extend
14413     // of an sextload into a sextload targeting a wider value.
14414     SDValue Load;
14415     if (MemSz == 128) {
14416       // Just switch this to a normal load.
14417       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14418                                        "it must be a legal 128-bit vector "
14419                                        "type!");
14420       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14421                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14422                   Ld->isInvariant(), Ld->getAlignment());
14423     } else {
14424       assert(MemSz < 128 &&
14425              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14426       // Do an sext load to a 128-bit vector type. We want to use the same
14427       // number of elements, but elements half as wide. This will end up being
14428       // recursively lowered by this routine, but will succeed as we definitely
14429       // have all the necessary features if we're using AVX1.
14430       EVT HalfEltVT =
14431           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14432       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14433       Load =
14434           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14435                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14436                          Ld->isNonTemporal(), Ld->isInvariant(),
14437                          Ld->getAlignment());
14438     }
14439
14440     // Replace chain users with the new chain.
14441     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14442     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14443
14444     // Finally, do a normal sign-extend to the desired register.
14445     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14446   }
14447
14448   // All sizes must be a power of two.
14449   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14450          "Non-power-of-two elements are not custom lowered!");
14451
14452   // Attempt to load the original value using scalar loads.
14453   // Find the largest scalar type that divides the total loaded size.
14454   MVT SclrLoadTy = MVT::i8;
14455   for (MVT Tp : MVT::integer_valuetypes()) {
14456     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14457       SclrLoadTy = Tp;
14458     }
14459   }
14460
14461   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14462   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14463       (64 <= MemSz))
14464     SclrLoadTy = MVT::f64;
14465
14466   // Calculate the number of scalar loads that we need to perform
14467   // in order to load our vector from memory.
14468   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14469
14470   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14471          "Can only lower sext loads with a single scalar load!");
14472
14473   unsigned loadRegZize = RegSz;
14474   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14475     loadRegZize = 128;
14476
14477   // Represent our vector as a sequence of elements which are the
14478   // largest scalar that we can load.
14479   EVT LoadUnitVecVT = EVT::getVectorVT(
14480       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14481
14482   // Represent the data using the same element type that is stored in
14483   // memory. In practice, we ''widen'' MemVT.
14484   EVT WideVecVT =
14485       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14486                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14487
14488   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14489          "Invalid vector type");
14490
14491   // We can't shuffle using an illegal type.
14492   assert(TLI.isTypeLegal(WideVecVT) &&
14493          "We only lower types that form legal widened vector types");
14494
14495   SmallVector<SDValue, 8> Chains;
14496   SDValue Ptr = Ld->getBasePtr();
14497   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14498                                       TLI.getPointerTy(DAG.getDataLayout()));
14499   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14500
14501   for (unsigned i = 0; i < NumLoads; ++i) {
14502     // Perform a single load.
14503     SDValue ScalarLoad =
14504         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14505                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14506                     Ld->getAlignment());
14507     Chains.push_back(ScalarLoad.getValue(1));
14508     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14509     // another round of DAGCombining.
14510     if (i == 0)
14511       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14512     else
14513       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14514                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14515
14516     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14517   }
14518
14519   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14520
14521   // Bitcast the loaded value to a vector of the original element type, in
14522   // the size of the target vector type.
14523   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14524   unsigned SizeRatio = RegSz / MemSz;
14525
14526   if (Ext == ISD::SEXTLOAD) {
14527     // If we have SSE4.1, we can directly emit a VSEXT node.
14528     if (Subtarget->hasSSE41()) {
14529       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14530       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14531       return Sext;
14532     }
14533
14534     // Otherwise we'll shuffle the small elements in the high bits of the
14535     // larger type and perform an arithmetic shift. If the shift is not legal
14536     // it's better to scalarize.
14537     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14538            "We can't implement a sext load without an arithmetic right shift!");
14539
14540     // Redistribute the loaded elements into the different locations.
14541     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14542     for (unsigned i = 0; i != NumElems; ++i)
14543       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14544
14545     SDValue Shuff = DAG.getVectorShuffle(
14546         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14547
14548     Shuff = DAG.getBitcast(RegVT, Shuff);
14549
14550     // Build the arithmetic shift.
14551     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14552                    MemVT.getVectorElementType().getSizeInBits();
14553     Shuff =
14554         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14555                     DAG.getConstant(Amt, dl, RegVT));
14556
14557     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14558     return Shuff;
14559   }
14560
14561   // Redistribute the loaded elements into the different locations.
14562   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14563   for (unsigned i = 0; i != NumElems; ++i)
14564     ShuffleVec[i * SizeRatio] = i;
14565
14566   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14567                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14568
14569   // Bitcast to the requested type.
14570   Shuff = DAG.getBitcast(RegVT, Shuff);
14571   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14572   return Shuff;
14573 }
14574
14575 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14576 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14577 // from the AND / OR.
14578 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14579   Opc = Op.getOpcode();
14580   if (Opc != ISD::OR && Opc != ISD::AND)
14581     return false;
14582   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14583           Op.getOperand(0).hasOneUse() &&
14584           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14585           Op.getOperand(1).hasOneUse());
14586 }
14587
14588 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14589 // 1 and that the SETCC node has a single use.
14590 static bool isXor1OfSetCC(SDValue Op) {
14591   if (Op.getOpcode() != ISD::XOR)
14592     return false;
14593   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14594   if (N1C && N1C->getAPIntValue() == 1) {
14595     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14596       Op.getOperand(0).hasOneUse();
14597   }
14598   return false;
14599 }
14600
14601 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14602   bool addTest = true;
14603   SDValue Chain = Op.getOperand(0);
14604   SDValue Cond  = Op.getOperand(1);
14605   SDValue Dest  = Op.getOperand(2);
14606   SDLoc dl(Op);
14607   SDValue CC;
14608   bool Inverted = false;
14609
14610   if (Cond.getOpcode() == ISD::SETCC) {
14611     // Check for setcc([su]{add,sub,mul}o == 0).
14612     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14613         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14614         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14615         Cond.getOperand(0).getResNo() == 1 &&
14616         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14617          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14618          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14619          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14620          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14621          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14622       Inverted = true;
14623       Cond = Cond.getOperand(0);
14624     } else {
14625       SDValue NewCond = LowerSETCC(Cond, DAG);
14626       if (NewCond.getNode())
14627         Cond = NewCond;
14628     }
14629   }
14630 #if 0
14631   // FIXME: LowerXALUO doesn't handle these!!
14632   else if (Cond.getOpcode() == X86ISD::ADD  ||
14633            Cond.getOpcode() == X86ISD::SUB  ||
14634            Cond.getOpcode() == X86ISD::SMUL ||
14635            Cond.getOpcode() == X86ISD::UMUL)
14636     Cond = LowerXALUO(Cond, DAG);
14637 #endif
14638
14639   // Look pass (and (setcc_carry (cmp ...)), 1).
14640   if (Cond.getOpcode() == ISD::AND &&
14641       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14642     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14643     if (C && C->getAPIntValue() == 1)
14644       Cond = Cond.getOperand(0);
14645   }
14646
14647   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14648   // setting operand in place of the X86ISD::SETCC.
14649   unsigned CondOpcode = Cond.getOpcode();
14650   if (CondOpcode == X86ISD::SETCC ||
14651       CondOpcode == X86ISD::SETCC_CARRY) {
14652     CC = Cond.getOperand(0);
14653
14654     SDValue Cmp = Cond.getOperand(1);
14655     unsigned Opc = Cmp.getOpcode();
14656     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14657     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14658       Cond = Cmp;
14659       addTest = false;
14660     } else {
14661       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14662       default: break;
14663       case X86::COND_O:
14664       case X86::COND_B:
14665         // These can only come from an arithmetic instruction with overflow,
14666         // e.g. SADDO, UADDO.
14667         Cond = Cond.getNode()->getOperand(1);
14668         addTest = false;
14669         break;
14670       }
14671     }
14672   }
14673   CondOpcode = Cond.getOpcode();
14674   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14675       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14676       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14677        Cond.getOperand(0).getValueType() != MVT::i8)) {
14678     SDValue LHS = Cond.getOperand(0);
14679     SDValue RHS = Cond.getOperand(1);
14680     unsigned X86Opcode;
14681     unsigned X86Cond;
14682     SDVTList VTs;
14683     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14684     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14685     // X86ISD::INC).
14686     switch (CondOpcode) {
14687     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14688     case ISD::SADDO:
14689       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14690         if (C->isOne()) {
14691           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14692           break;
14693         }
14694       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14695     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14696     case ISD::SSUBO:
14697       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14698         if (C->isOne()) {
14699           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14700           break;
14701         }
14702       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14703     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14704     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14705     default: llvm_unreachable("unexpected overflowing operator");
14706     }
14707     if (Inverted)
14708       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14709     if (CondOpcode == ISD::UMULO)
14710       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14711                           MVT::i32);
14712     else
14713       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14714
14715     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14716
14717     if (CondOpcode == ISD::UMULO)
14718       Cond = X86Op.getValue(2);
14719     else
14720       Cond = X86Op.getValue(1);
14721
14722     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14723     addTest = false;
14724   } else {
14725     unsigned CondOpc;
14726     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14727       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14728       if (CondOpc == ISD::OR) {
14729         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14730         // two branches instead of an explicit OR instruction with a
14731         // separate test.
14732         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14733             isX86LogicalCmp(Cmp)) {
14734           CC = Cond.getOperand(0).getOperand(0);
14735           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14736                               Chain, Dest, CC, Cmp);
14737           CC = Cond.getOperand(1).getOperand(0);
14738           Cond = Cmp;
14739           addTest = false;
14740         }
14741       } else { // ISD::AND
14742         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14743         // two branches instead of an explicit AND instruction with a
14744         // separate test. However, we only do this if this block doesn't
14745         // have a fall-through edge, because this requires an explicit
14746         // jmp when the condition is false.
14747         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14748             isX86LogicalCmp(Cmp) &&
14749             Op.getNode()->hasOneUse()) {
14750           X86::CondCode CCode =
14751             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14752           CCode = X86::GetOppositeBranchCondition(CCode);
14753           CC = DAG.getConstant(CCode, dl, MVT::i8);
14754           SDNode *User = *Op.getNode()->use_begin();
14755           // Look for an unconditional branch following this conditional branch.
14756           // We need this because we need to reverse the successors in order
14757           // to implement FCMP_OEQ.
14758           if (User->getOpcode() == ISD::BR) {
14759             SDValue FalseBB = User->getOperand(1);
14760             SDNode *NewBR =
14761               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14762             assert(NewBR == User);
14763             (void)NewBR;
14764             Dest = FalseBB;
14765
14766             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14767                                 Chain, Dest, CC, Cmp);
14768             X86::CondCode CCode =
14769               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14770             CCode = X86::GetOppositeBranchCondition(CCode);
14771             CC = DAG.getConstant(CCode, dl, MVT::i8);
14772             Cond = Cmp;
14773             addTest = false;
14774           }
14775         }
14776       }
14777     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14778       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14779       // It should be transformed during dag combiner except when the condition
14780       // is set by a arithmetics with overflow node.
14781       X86::CondCode CCode =
14782         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14783       CCode = X86::GetOppositeBranchCondition(CCode);
14784       CC = DAG.getConstant(CCode, dl, MVT::i8);
14785       Cond = Cond.getOperand(0).getOperand(1);
14786       addTest = false;
14787     } else if (Cond.getOpcode() == ISD::SETCC &&
14788                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14789       // For FCMP_OEQ, we can emit
14790       // two branches instead of an explicit AND instruction with a
14791       // separate test. However, we only do this if this block doesn't
14792       // have a fall-through edge, because this requires an explicit
14793       // jmp when the condition is false.
14794       if (Op.getNode()->hasOneUse()) {
14795         SDNode *User = *Op.getNode()->use_begin();
14796         // Look for an unconditional branch following this conditional branch.
14797         // We need this because we need to reverse the successors in order
14798         // to implement FCMP_OEQ.
14799         if (User->getOpcode() == ISD::BR) {
14800           SDValue FalseBB = User->getOperand(1);
14801           SDNode *NewBR =
14802             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14803           assert(NewBR == User);
14804           (void)NewBR;
14805           Dest = FalseBB;
14806
14807           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14808                                     Cond.getOperand(0), Cond.getOperand(1));
14809           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14810           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14811           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14812                               Chain, Dest, CC, Cmp);
14813           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14814           Cond = Cmp;
14815           addTest = false;
14816         }
14817       }
14818     } else if (Cond.getOpcode() == ISD::SETCC &&
14819                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14820       // For FCMP_UNE, we can emit
14821       // two branches instead of an explicit AND instruction with a
14822       // separate test. However, we only do this if this block doesn't
14823       // have a fall-through edge, because this requires an explicit
14824       // jmp when the condition is false.
14825       if (Op.getNode()->hasOneUse()) {
14826         SDNode *User = *Op.getNode()->use_begin();
14827         // Look for an unconditional branch following this conditional branch.
14828         // We need this because we need to reverse the successors in order
14829         // to implement FCMP_UNE.
14830         if (User->getOpcode() == ISD::BR) {
14831           SDValue FalseBB = User->getOperand(1);
14832           SDNode *NewBR =
14833             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14834           assert(NewBR == User);
14835           (void)NewBR;
14836
14837           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14838                                     Cond.getOperand(0), Cond.getOperand(1));
14839           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14840           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14841           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14842                               Chain, Dest, CC, Cmp);
14843           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14844           Cond = Cmp;
14845           addTest = false;
14846           Dest = FalseBB;
14847         }
14848       }
14849     }
14850   }
14851
14852   if (addTest) {
14853     // Look pass the truncate if the high bits are known zero.
14854     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14855         Cond = Cond.getOperand(0);
14856
14857     // We know the result of AND is compared against zero. Try to match
14858     // it to BT.
14859     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14860       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14861       if (NewSetCC.getNode()) {
14862         CC = NewSetCC.getOperand(0);
14863         Cond = NewSetCC.getOperand(1);
14864         addTest = false;
14865       }
14866     }
14867   }
14868
14869   if (addTest) {
14870     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14871     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14872     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14873   }
14874   Cond = ConvertCmpIfNecessary(Cond, DAG);
14875   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14876                      Chain, Dest, CC, Cond);
14877 }
14878
14879 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14880 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14881 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14882 // that the guard pages used by the OS virtual memory manager are allocated in
14883 // correct sequence.
14884 SDValue
14885 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14886                                            SelectionDAG &DAG) const {
14887   MachineFunction &MF = DAG.getMachineFunction();
14888   bool SplitStack = MF.shouldSplitStack();
14889   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14890                SplitStack;
14891   SDLoc dl(Op);
14892
14893   if (!Lower) {
14894     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14895     SDNode* Node = Op.getNode();
14896
14897     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14898     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14899         " not tell us which reg is the stack pointer!");
14900     EVT VT = Node->getValueType(0);
14901     SDValue Tmp1 = SDValue(Node, 0);
14902     SDValue Tmp2 = SDValue(Node, 1);
14903     SDValue Tmp3 = Node->getOperand(2);
14904     SDValue Chain = Tmp1.getOperand(0);
14905
14906     // Chain the dynamic stack allocation so that it doesn't modify the stack
14907     // pointer when other instructions are using the stack.
14908     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14909         SDLoc(Node));
14910
14911     SDValue Size = Tmp2.getOperand(1);
14912     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14913     Chain = SP.getValue(1);
14914     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14915     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14916     unsigned StackAlign = TFI.getStackAlignment();
14917     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14918     if (Align > StackAlign)
14919       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14920           DAG.getConstant(-(uint64_t)Align, dl, VT));
14921     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14922
14923     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14924         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14925         SDLoc(Node));
14926
14927     SDValue Ops[2] = { Tmp1, Tmp2 };
14928     return DAG.getMergeValues(Ops, dl);
14929   }
14930
14931   // Get the inputs.
14932   SDValue Chain = Op.getOperand(0);
14933   SDValue Size  = Op.getOperand(1);
14934   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14935   EVT VT = Op.getNode()->getValueType(0);
14936
14937   bool Is64Bit = Subtarget->is64Bit();
14938   MVT SPTy = getPointerTy(DAG.getDataLayout());
14939
14940   if (SplitStack) {
14941     MachineRegisterInfo &MRI = MF.getRegInfo();
14942
14943     if (Is64Bit) {
14944       // The 64 bit implementation of segmented stacks needs to clobber both r10
14945       // r11. This makes it impossible to use it along with nested parameters.
14946       const Function *F = MF.getFunction();
14947
14948       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14949            I != E; ++I)
14950         if (I->hasNestAttr())
14951           report_fatal_error("Cannot use segmented stacks with functions that "
14952                              "have nested arguments.");
14953     }
14954
14955     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14956     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14957     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14958     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14959                                 DAG.getRegister(Vreg, SPTy));
14960     SDValue Ops1[2] = { Value, Chain };
14961     return DAG.getMergeValues(Ops1, dl);
14962   } else {
14963     SDValue Flag;
14964     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14965
14966     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14967     Flag = Chain.getValue(1);
14968     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14969
14970     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14971
14972     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14973     unsigned SPReg = RegInfo->getStackRegister();
14974     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14975     Chain = SP.getValue(1);
14976
14977     if (Align) {
14978       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14979                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14980       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14981     }
14982
14983     SDValue Ops1[2] = { SP, Chain };
14984     return DAG.getMergeValues(Ops1, dl);
14985   }
14986 }
14987
14988 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14989   MachineFunction &MF = DAG.getMachineFunction();
14990   auto PtrVT = getPointerTy(MF.getDataLayout());
14991   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14992
14993   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14994   SDLoc DL(Op);
14995
14996   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14997     // vastart just stores the address of the VarArgsFrameIndex slot into the
14998     // memory location argument.
14999     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15000     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15001                         MachinePointerInfo(SV), false, false, 0);
15002   }
15003
15004   // __va_list_tag:
15005   //   gp_offset         (0 - 6 * 8)
15006   //   fp_offset         (48 - 48 + 8 * 16)
15007   //   overflow_arg_area (point to parameters coming in memory).
15008   //   reg_save_area
15009   SmallVector<SDValue, 8> MemOps;
15010   SDValue FIN = Op.getOperand(1);
15011   // Store gp_offset
15012   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15013                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15014                                                DL, MVT::i32),
15015                                FIN, MachinePointerInfo(SV), false, false, 0);
15016   MemOps.push_back(Store);
15017
15018   // Store fp_offset
15019   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15020   Store = DAG.getStore(Op.getOperand(0), DL,
15021                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15022                                        MVT::i32),
15023                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15024   MemOps.push_back(Store);
15025
15026   // Store ptr to overflow_arg_area
15027   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15028   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15029   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15030                        MachinePointerInfo(SV, 8),
15031                        false, false, 0);
15032   MemOps.push_back(Store);
15033
15034   // Store ptr to reg_save_area.
15035   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15036   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15037   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15038                        MachinePointerInfo(SV, 16), false, false, 0);
15039   MemOps.push_back(Store);
15040   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15041 }
15042
15043 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15044   assert(Subtarget->is64Bit() &&
15045          "LowerVAARG only handles 64-bit va_arg!");
15046   assert((Subtarget->isTargetLinux() ||
15047           Subtarget->isTargetDarwin()) &&
15048           "Unhandled target in LowerVAARG");
15049   assert(Op.getNode()->getNumOperands() == 4);
15050   SDValue Chain = Op.getOperand(0);
15051   SDValue SrcPtr = Op.getOperand(1);
15052   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15053   unsigned Align = Op.getConstantOperandVal(3);
15054   SDLoc dl(Op);
15055
15056   EVT ArgVT = Op.getNode()->getValueType(0);
15057   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15058   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15059   uint8_t ArgMode;
15060
15061   // Decide which area this value should be read from.
15062   // TODO: Implement the AMD64 ABI in its entirety. This simple
15063   // selection mechanism works only for the basic types.
15064   if (ArgVT == MVT::f80) {
15065     llvm_unreachable("va_arg for f80 not yet implemented");
15066   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15067     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15068   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15069     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15070   } else {
15071     llvm_unreachable("Unhandled argument type in LowerVAARG");
15072   }
15073
15074   if (ArgMode == 2) {
15075     // Sanity Check: Make sure using fp_offset makes sense.
15076     assert(!Subtarget->useSoftFloat() &&
15077            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15078                Attribute::NoImplicitFloat)) &&
15079            Subtarget->hasSSE1());
15080   }
15081
15082   // Insert VAARG_64 node into the DAG
15083   // VAARG_64 returns two values: Variable Argument Address, Chain
15084   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15085                        DAG.getConstant(ArgMode, dl, MVT::i8),
15086                        DAG.getConstant(Align, dl, MVT::i32)};
15087   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15088   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15089                                           VTs, InstOps, MVT::i64,
15090                                           MachinePointerInfo(SV),
15091                                           /*Align=*/0,
15092                                           /*Volatile=*/false,
15093                                           /*ReadMem=*/true,
15094                                           /*WriteMem=*/true);
15095   Chain = VAARG.getValue(1);
15096
15097   // Load the next argument and return it
15098   return DAG.getLoad(ArgVT, dl,
15099                      Chain,
15100                      VAARG,
15101                      MachinePointerInfo(),
15102                      false, false, false, 0);
15103 }
15104
15105 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15106                            SelectionDAG &DAG) {
15107   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15108   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15109   SDValue Chain = Op.getOperand(0);
15110   SDValue DstPtr = Op.getOperand(1);
15111   SDValue SrcPtr = Op.getOperand(2);
15112   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15113   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15114   SDLoc DL(Op);
15115
15116   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15117                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15118                        false, false,
15119                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15120 }
15121
15122 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15123 // amount is a constant. Takes immediate version of shift as input.
15124 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15125                                           SDValue SrcOp, uint64_t ShiftAmt,
15126                                           SelectionDAG &DAG) {
15127   MVT ElementType = VT.getVectorElementType();
15128
15129   // Fold this packed shift into its first operand if ShiftAmt is 0.
15130   if (ShiftAmt == 0)
15131     return SrcOp;
15132
15133   // Check for ShiftAmt >= element width
15134   if (ShiftAmt >= ElementType.getSizeInBits()) {
15135     if (Opc == X86ISD::VSRAI)
15136       ShiftAmt = ElementType.getSizeInBits() - 1;
15137     else
15138       return DAG.getConstant(0, dl, VT);
15139   }
15140
15141   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15142          && "Unknown target vector shift-by-constant node");
15143
15144   // Fold this packed vector shift into a build vector if SrcOp is a
15145   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15146   if (VT == SrcOp.getSimpleValueType() &&
15147       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15148     SmallVector<SDValue, 8> Elts;
15149     unsigned NumElts = SrcOp->getNumOperands();
15150     ConstantSDNode *ND;
15151
15152     switch(Opc) {
15153     default: llvm_unreachable(nullptr);
15154     case X86ISD::VSHLI:
15155       for (unsigned i=0; i!=NumElts; ++i) {
15156         SDValue CurrentOp = SrcOp->getOperand(i);
15157         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15158           Elts.push_back(CurrentOp);
15159           continue;
15160         }
15161         ND = cast<ConstantSDNode>(CurrentOp);
15162         const APInt &C = ND->getAPIntValue();
15163         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15164       }
15165       break;
15166     case X86ISD::VSRLI:
15167       for (unsigned i=0; i!=NumElts; ++i) {
15168         SDValue CurrentOp = SrcOp->getOperand(i);
15169         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15170           Elts.push_back(CurrentOp);
15171           continue;
15172         }
15173         ND = cast<ConstantSDNode>(CurrentOp);
15174         const APInt &C = ND->getAPIntValue();
15175         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15176       }
15177       break;
15178     case X86ISD::VSRAI:
15179       for (unsigned i=0; i!=NumElts; ++i) {
15180         SDValue CurrentOp = SrcOp->getOperand(i);
15181         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15182           Elts.push_back(CurrentOp);
15183           continue;
15184         }
15185         ND = cast<ConstantSDNode>(CurrentOp);
15186         const APInt &C = ND->getAPIntValue();
15187         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15188       }
15189       break;
15190     }
15191
15192     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15193   }
15194
15195   return DAG.getNode(Opc, dl, VT, SrcOp,
15196                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15197 }
15198
15199 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15200 // may or may not be a constant. Takes immediate version of shift as input.
15201 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15202                                    SDValue SrcOp, SDValue ShAmt,
15203                                    SelectionDAG &DAG) {
15204   MVT SVT = ShAmt.getSimpleValueType();
15205   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15206
15207   // Catch shift-by-constant.
15208   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15209     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15210                                       CShAmt->getZExtValue(), DAG);
15211
15212   // Change opcode to non-immediate version
15213   switch (Opc) {
15214     default: llvm_unreachable("Unknown target vector shift node");
15215     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15216     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15217     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15218   }
15219
15220   const X86Subtarget &Subtarget =
15221       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15222   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15223       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15224     // Let the shuffle legalizer expand this shift amount node.
15225     SDValue Op0 = ShAmt.getOperand(0);
15226     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15227     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15228   } else {
15229     // Need to build a vector containing shift amount.
15230     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15231     SmallVector<SDValue, 4> ShOps;
15232     ShOps.push_back(ShAmt);
15233     if (SVT == MVT::i32) {
15234       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15235       ShOps.push_back(DAG.getUNDEF(SVT));
15236     }
15237     ShOps.push_back(DAG.getUNDEF(SVT));
15238
15239     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15240     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15241   }
15242
15243   // The return type has to be a 128-bit type with the same element
15244   // type as the input type.
15245   MVT EltVT = VT.getVectorElementType();
15246   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15247
15248   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15249   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15250 }
15251
15252 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15253 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15254 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15255 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15256                                     SDValue PreservedSrc,
15257                                     const X86Subtarget *Subtarget,
15258                                     SelectionDAG &DAG) {
15259     EVT VT = Op.getValueType();
15260     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15261                                   MVT::i1, VT.getVectorNumElements());
15262     SDValue VMask = SDValue();
15263     unsigned OpcodeSelect = ISD::VSELECT;
15264     SDLoc dl(Op);
15265
15266     assert(MaskVT.isSimple() && "invalid mask type");
15267
15268     if (isAllOnes(Mask))
15269       return Op;
15270
15271     if (MaskVT.bitsGT(Mask.getValueType())) {
15272       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15273                                          MaskVT.getSizeInBits());
15274       VMask = DAG.getBitcast(MaskVT,
15275                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15276     } else {
15277       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15278                                        Mask.getValueType().getSizeInBits());
15279       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15280       // are extracted by EXTRACT_SUBVECTOR.
15281       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15282                           DAG.getBitcast(BitcastVT, Mask),
15283                           DAG.getIntPtrConstant(0, dl));
15284     }
15285
15286     switch (Op.getOpcode()) {
15287       default: break;
15288       case X86ISD::PCMPEQM:
15289       case X86ISD::PCMPGTM:
15290       case X86ISD::CMPM:
15291       case X86ISD::CMPMU:
15292         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15293       case X86ISD::VTRUNC:
15294       case X86ISD::VTRUNCS:
15295       case X86ISD::VTRUNCUS:
15296         // We can't use ISD::VSELECT here because it is not always "Legal"
15297         // for the destination type. For example vpmovqb require only AVX512
15298         // and vselect that can operate on byte element type require BWI
15299         OpcodeSelect = X86ISD::SELECT;
15300         break;
15301     }
15302     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15303       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15304     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15305 }
15306
15307 /// \brief Creates an SDNode for a predicated scalar operation.
15308 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15309 /// The mask is coming as MVT::i8 and it should be truncated
15310 /// to MVT::i1 while lowering masking intrinsics.
15311 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15312 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15313 /// for a scalar instruction.
15314 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15315                                     SDValue PreservedSrc,
15316                                     const X86Subtarget *Subtarget,
15317                                     SelectionDAG &DAG) {
15318     if (isAllOnes(Mask))
15319       return Op;
15320
15321     EVT VT = Op.getValueType();
15322     SDLoc dl(Op);
15323     // The mask should be of type MVT::i1
15324     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15325
15326     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15327       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15328     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15329 }
15330
15331 static int getSEHRegistrationNodeSize(const Function *Fn) {
15332   if (!Fn->hasPersonalityFn())
15333     report_fatal_error(
15334         "querying registration node size for function without personality");
15335   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15336   // WinEHStatePass for the full struct definition.
15337   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15338   case EHPersonality::MSVC_X86SEH: return 24;
15339   case EHPersonality::MSVC_CXX: return 16;
15340   default: break;
15341   }
15342   report_fatal_error("can only recover FP for MSVC EH personality functions");
15343 }
15344
15345 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15346 /// function or when returning to a parent frame after catching an exception, we
15347 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15348 /// Here's the math:
15349 ///   RegNodeBase = EntryEBP - RegNodeSize
15350 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15351 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15352 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15353 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15354                                    SDValue EntryEBP) {
15355   MachineFunction &MF = DAG.getMachineFunction();
15356   SDLoc dl;
15357
15358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15359   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15360
15361   // It's possible that the parent function no longer has a personality function
15362   // if the exceptional code was optimized away, in which case we just return
15363   // the incoming EBP.
15364   if (!Fn->hasPersonalityFn())
15365     return EntryEBP;
15366
15367   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15368
15369   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15370   // registration.
15371   MCSymbol *OffsetSym =
15372       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15373           GlobalValue::getRealLinkageName(Fn->getName()));
15374   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15375   SDValue RegNodeFrameOffset =
15376       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15377
15378   // RegNodeBase = EntryEBP - RegNodeSize
15379   // ParentFP = RegNodeBase - RegNodeFrameOffset
15380   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15381                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15382   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15383 }
15384
15385 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15386                                        SelectionDAG &DAG) {
15387   SDLoc dl(Op);
15388   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15389   EVT VT = Op.getValueType();
15390   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15391   if (IntrData) {
15392     switch(IntrData->Type) {
15393     case INTR_TYPE_1OP:
15394       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15395     case INTR_TYPE_2OP:
15396       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15397         Op.getOperand(2));
15398     case INTR_TYPE_3OP:
15399       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15400         Op.getOperand(2), Op.getOperand(3));
15401     case INTR_TYPE_4OP:
15402       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15403         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15404     case INTR_TYPE_1OP_MASK_RM: {
15405       SDValue Src = Op.getOperand(1);
15406       SDValue PassThru = Op.getOperand(2);
15407       SDValue Mask = Op.getOperand(3);
15408       SDValue RoundingMode;
15409       // We allways add rounding mode to the Node.
15410       // If the rounding mode is not specified, we add the 
15411       // "current direction" mode.
15412       if (Op.getNumOperands() == 4)
15413         RoundingMode =
15414           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15415       else
15416         RoundingMode = Op.getOperand(4);
15417       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15418       if (IntrWithRoundingModeOpcode != 0)
15419         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15420             X86::STATIC_ROUNDING::CUR_DIRECTION)
15421           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15422                                       dl, Op.getValueType(), Src, RoundingMode),
15423                                       Mask, PassThru, Subtarget, DAG);
15424       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15425                                               RoundingMode),
15426                                   Mask, PassThru, Subtarget, DAG);
15427     }
15428     case INTR_TYPE_1OP_MASK: {
15429       SDValue Src = Op.getOperand(1);
15430       SDValue PassThru = Op.getOperand(2);
15431       SDValue Mask = Op.getOperand(3);
15432       // We add rounding mode to the Node when
15433       //   - RM Opcode is specified and
15434       //   - RM is not "current direction".
15435       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15436       if (IntrWithRoundingModeOpcode != 0) {
15437         SDValue Rnd = Op.getOperand(4);
15438         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15439         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15440           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15441                                       dl, Op.getValueType(),
15442                                       Src, Rnd),
15443                                       Mask, PassThru, Subtarget, DAG);
15444         }
15445       }
15446       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15447                                   Mask, PassThru, Subtarget, DAG);
15448     }
15449     case INTR_TYPE_SCALAR_MASK_RM: {
15450       SDValue Src1 = Op.getOperand(1);
15451       SDValue Src2 = Op.getOperand(2);
15452       SDValue Src0 = Op.getOperand(3);
15453       SDValue Mask = Op.getOperand(4);
15454       // There are 2 kinds of intrinsics in this group:
15455       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15456       // (2) With rounding mode and sae - 7 operands.
15457       if (Op.getNumOperands() == 6) {
15458         SDValue Sae  = Op.getOperand(5);
15459         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15460         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15461                                                 Sae),
15462                                     Mask, Src0, Subtarget, DAG);
15463       }
15464       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15465       SDValue RoundingMode  = Op.getOperand(5);
15466       SDValue Sae  = Op.getOperand(6);
15467       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15468                                               RoundingMode, Sae),
15469                                   Mask, Src0, Subtarget, DAG);
15470     }
15471     case INTR_TYPE_2OP_MASK: {
15472       SDValue Src1 = Op.getOperand(1);
15473       SDValue Src2 = Op.getOperand(2);
15474       SDValue PassThru = Op.getOperand(3);
15475       SDValue Mask = Op.getOperand(4);
15476       // We specify 2 possible opcodes for intrinsics with rounding modes.
15477       // First, we check if the intrinsic may have non-default rounding mode,
15478       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15479       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15480       if (IntrWithRoundingModeOpcode != 0) {
15481         SDValue Rnd = Op.getOperand(5);
15482         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15483         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15484           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15485                                       dl, Op.getValueType(),
15486                                       Src1, Src2, Rnd),
15487                                       Mask, PassThru, Subtarget, DAG);
15488         }
15489       }
15490       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15491                                               Src1,Src2),
15492                                   Mask, PassThru, Subtarget, DAG);
15493     }
15494     case INTR_TYPE_2OP_MASK_RM: {
15495       SDValue Src1 = Op.getOperand(1);
15496       SDValue Src2 = Op.getOperand(2);
15497       SDValue PassThru = Op.getOperand(3);
15498       SDValue Mask = Op.getOperand(4);
15499       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15500       // First, we check if the intrinsic have rounding mode (6 operands),
15501       // if not, we set rounding mode to "current".
15502       SDValue Rnd;
15503       if (Op.getNumOperands() == 6)
15504         Rnd = Op.getOperand(5);
15505       else
15506         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15507       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15508                                               Src1, Src2, Rnd),
15509                                   Mask, PassThru, Subtarget, DAG);
15510     }
15511     case INTR_TYPE_3OP_MASK_RM: {
15512       SDValue Src1 = Op.getOperand(1);
15513       SDValue Src2 = Op.getOperand(2);
15514       SDValue Imm = Op.getOperand(3);
15515       SDValue PassThru = Op.getOperand(4);
15516       SDValue Mask = Op.getOperand(5);
15517       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15518       // First, we check if the intrinsic have rounding mode (7 operands),
15519       // if not, we set rounding mode to "current".
15520       SDValue Rnd;
15521       if (Op.getNumOperands() == 7)
15522         Rnd = Op.getOperand(6);
15523       else
15524         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15525       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15526         Src1, Src2, Imm, Rnd),
15527         Mask, PassThru, Subtarget, DAG);
15528     }
15529     case INTR_TYPE_3OP_MASK: {
15530       SDValue Src1 = Op.getOperand(1);
15531       SDValue Src2 = Op.getOperand(2);
15532       SDValue Src3 = Op.getOperand(3);
15533       SDValue PassThru = Op.getOperand(4);
15534       SDValue Mask = Op.getOperand(5);
15535       // We specify 2 possible opcodes for intrinsics with rounding modes.
15536       // First, we check if the intrinsic may have non-default rounding mode,
15537       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15538       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15539       if (IntrWithRoundingModeOpcode != 0) {
15540         SDValue Rnd = Op.getOperand(6);
15541         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15542         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15543           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15544                                       dl, Op.getValueType(),
15545                                       Src1, Src2, Src3, Rnd),
15546                                       Mask, PassThru, Subtarget, DAG);
15547         }
15548       }
15549       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15550                                               Src1, Src2, Src3),
15551                                   Mask, PassThru, Subtarget, DAG);
15552     }
15553     case VPERM_3OP_MASKZ:
15554     case VPERM_3OP_MASK:
15555     case FMA_OP_MASK3:
15556     case FMA_OP_MASKZ:
15557     case FMA_OP_MASK: {
15558       SDValue Src1 = Op.getOperand(1);
15559       SDValue Src2 = Op.getOperand(2);
15560       SDValue Src3 = Op.getOperand(3);
15561       SDValue Mask = Op.getOperand(4);
15562       EVT VT = Op.getValueType();
15563       SDValue PassThru = SDValue();
15564
15565       // set PassThru element
15566       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15567         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15568       else if (IntrData->Type == FMA_OP_MASK3)
15569         PassThru = Src3;
15570       else
15571         PassThru = Src1;
15572
15573       // We specify 2 possible opcodes for intrinsics with rounding modes.
15574       // First, we check if the intrinsic may have non-default rounding mode,
15575       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15576       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15577       if (IntrWithRoundingModeOpcode != 0) {
15578         SDValue Rnd = Op.getOperand(5);
15579         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15580             X86::STATIC_ROUNDING::CUR_DIRECTION)
15581           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15582                                                   dl, Op.getValueType(),
15583                                                   Src1, Src2, Src3, Rnd),
15584                                       Mask, PassThru, Subtarget, DAG);
15585       }
15586       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15587                                               dl, Op.getValueType(),
15588                                               Src1, Src2, Src3),
15589                                   Mask, PassThru, Subtarget, DAG);
15590     }
15591     case CMP_MASK:
15592     case CMP_MASK_CC: {
15593       // Comparison intrinsics with masks.
15594       // Example of transformation:
15595       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15596       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15597       // (i8 (bitcast
15598       //   (v8i1 (insert_subvector undef,
15599       //           (v2i1 (and (PCMPEQM %a, %b),
15600       //                      (extract_subvector
15601       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15602       EVT VT = Op.getOperand(1).getValueType();
15603       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15604                                     VT.getVectorNumElements());
15605       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15606       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15607                                        Mask.getValueType().getSizeInBits());
15608       SDValue Cmp;
15609       if (IntrData->Type == CMP_MASK_CC) {
15610         SDValue CC = Op.getOperand(3);
15611         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15612         // We specify 2 possible opcodes for intrinsics with rounding modes.
15613         // First, we check if the intrinsic may have non-default rounding mode,
15614         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15615         if (IntrData->Opc1 != 0) {
15616           SDValue Rnd = Op.getOperand(5);
15617           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15618               X86::STATIC_ROUNDING::CUR_DIRECTION)
15619             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15620                               Op.getOperand(2), CC, Rnd);
15621         }
15622         //default rounding mode
15623         if(!Cmp.getNode())
15624             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15625                               Op.getOperand(2), CC);
15626
15627       } else {
15628         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15629         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15630                           Op.getOperand(2));
15631       }
15632       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15633                                              DAG.getTargetConstant(0, dl,
15634                                                                    MaskVT),
15635                                              Subtarget, DAG);
15636       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15637                                 DAG.getUNDEF(BitcastVT), CmpMask,
15638                                 DAG.getIntPtrConstant(0, dl));
15639       return DAG.getBitcast(Op.getValueType(), Res);
15640     }
15641     case COMI: { // Comparison intrinsics
15642       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15643       SDValue LHS = Op.getOperand(1);
15644       SDValue RHS = Op.getOperand(2);
15645       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15646       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15647       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15648       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15649                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15650       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15651     }
15652     case VSHIFT:
15653       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15654                                  Op.getOperand(1), Op.getOperand(2), DAG);
15655     case VSHIFT_MASK:
15656       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15657                                                       Op.getSimpleValueType(),
15658                                                       Op.getOperand(1),
15659                                                       Op.getOperand(2), DAG),
15660                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15661                                   DAG);
15662     case COMPRESS_EXPAND_IN_REG: {
15663       SDValue Mask = Op.getOperand(3);
15664       SDValue DataToCompress = Op.getOperand(1);
15665       SDValue PassThru = Op.getOperand(2);
15666       if (isAllOnes(Mask)) // return data as is
15667         return Op.getOperand(1);
15668
15669       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15670                                               DataToCompress),
15671                                   Mask, PassThru, Subtarget, DAG);
15672     }
15673     case BLEND: {
15674       SDValue Mask = Op.getOperand(3);
15675       EVT VT = Op.getValueType();
15676       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15677                                     VT.getVectorNumElements());
15678       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15679                                        Mask.getValueType().getSizeInBits());
15680       SDLoc dl(Op);
15681       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15682                                   DAG.getBitcast(BitcastVT, Mask),
15683                                   DAG.getIntPtrConstant(0, dl));
15684       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15685                          Op.getOperand(2));
15686     }
15687     default:
15688       break;
15689     }
15690   }
15691
15692   switch (IntNo) {
15693   default: return SDValue();    // Don't custom lower most intrinsics.
15694
15695   case Intrinsic::x86_avx2_permd:
15696   case Intrinsic::x86_avx2_permps:
15697     // Operands intentionally swapped. Mask is last operand to intrinsic,
15698     // but second operand for node/instruction.
15699     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15700                        Op.getOperand(2), Op.getOperand(1));
15701
15702   // ptest and testp intrinsics. The intrinsic these come from are designed to
15703   // return an integer value, not just an instruction so lower it to the ptest
15704   // or testp pattern and a setcc for the result.
15705   case Intrinsic::x86_sse41_ptestz:
15706   case Intrinsic::x86_sse41_ptestc:
15707   case Intrinsic::x86_sse41_ptestnzc:
15708   case Intrinsic::x86_avx_ptestz_256:
15709   case Intrinsic::x86_avx_ptestc_256:
15710   case Intrinsic::x86_avx_ptestnzc_256:
15711   case Intrinsic::x86_avx_vtestz_ps:
15712   case Intrinsic::x86_avx_vtestc_ps:
15713   case Intrinsic::x86_avx_vtestnzc_ps:
15714   case Intrinsic::x86_avx_vtestz_pd:
15715   case Intrinsic::x86_avx_vtestc_pd:
15716   case Intrinsic::x86_avx_vtestnzc_pd:
15717   case Intrinsic::x86_avx_vtestz_ps_256:
15718   case Intrinsic::x86_avx_vtestc_ps_256:
15719   case Intrinsic::x86_avx_vtestnzc_ps_256:
15720   case Intrinsic::x86_avx_vtestz_pd_256:
15721   case Intrinsic::x86_avx_vtestc_pd_256:
15722   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15723     bool IsTestPacked = false;
15724     unsigned X86CC;
15725     switch (IntNo) {
15726     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15727     case Intrinsic::x86_avx_vtestz_ps:
15728     case Intrinsic::x86_avx_vtestz_pd:
15729     case Intrinsic::x86_avx_vtestz_ps_256:
15730     case Intrinsic::x86_avx_vtestz_pd_256:
15731       IsTestPacked = true; // Fallthrough
15732     case Intrinsic::x86_sse41_ptestz:
15733     case Intrinsic::x86_avx_ptestz_256:
15734       // ZF = 1
15735       X86CC = X86::COND_E;
15736       break;
15737     case Intrinsic::x86_avx_vtestc_ps:
15738     case Intrinsic::x86_avx_vtestc_pd:
15739     case Intrinsic::x86_avx_vtestc_ps_256:
15740     case Intrinsic::x86_avx_vtestc_pd_256:
15741       IsTestPacked = true; // Fallthrough
15742     case Intrinsic::x86_sse41_ptestc:
15743     case Intrinsic::x86_avx_ptestc_256:
15744       // CF = 1
15745       X86CC = X86::COND_B;
15746       break;
15747     case Intrinsic::x86_avx_vtestnzc_ps:
15748     case Intrinsic::x86_avx_vtestnzc_pd:
15749     case Intrinsic::x86_avx_vtestnzc_ps_256:
15750     case Intrinsic::x86_avx_vtestnzc_pd_256:
15751       IsTestPacked = true; // Fallthrough
15752     case Intrinsic::x86_sse41_ptestnzc:
15753     case Intrinsic::x86_avx_ptestnzc_256:
15754       // ZF and CF = 0
15755       X86CC = X86::COND_A;
15756       break;
15757     }
15758
15759     SDValue LHS = Op.getOperand(1);
15760     SDValue RHS = Op.getOperand(2);
15761     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15762     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15763     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15764     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15765     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15766   }
15767   case Intrinsic::x86_avx512_kortestz_w:
15768   case Intrinsic::x86_avx512_kortestc_w: {
15769     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15770     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15771     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15772     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15773     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15774     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15775     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15776   }
15777
15778   case Intrinsic::x86_sse42_pcmpistria128:
15779   case Intrinsic::x86_sse42_pcmpestria128:
15780   case Intrinsic::x86_sse42_pcmpistric128:
15781   case Intrinsic::x86_sse42_pcmpestric128:
15782   case Intrinsic::x86_sse42_pcmpistrio128:
15783   case Intrinsic::x86_sse42_pcmpestrio128:
15784   case Intrinsic::x86_sse42_pcmpistris128:
15785   case Intrinsic::x86_sse42_pcmpestris128:
15786   case Intrinsic::x86_sse42_pcmpistriz128:
15787   case Intrinsic::x86_sse42_pcmpestriz128: {
15788     unsigned Opcode;
15789     unsigned X86CC;
15790     switch (IntNo) {
15791     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15792     case Intrinsic::x86_sse42_pcmpistria128:
15793       Opcode = X86ISD::PCMPISTRI;
15794       X86CC = X86::COND_A;
15795       break;
15796     case Intrinsic::x86_sse42_pcmpestria128:
15797       Opcode = X86ISD::PCMPESTRI;
15798       X86CC = X86::COND_A;
15799       break;
15800     case Intrinsic::x86_sse42_pcmpistric128:
15801       Opcode = X86ISD::PCMPISTRI;
15802       X86CC = X86::COND_B;
15803       break;
15804     case Intrinsic::x86_sse42_pcmpestric128:
15805       Opcode = X86ISD::PCMPESTRI;
15806       X86CC = X86::COND_B;
15807       break;
15808     case Intrinsic::x86_sse42_pcmpistrio128:
15809       Opcode = X86ISD::PCMPISTRI;
15810       X86CC = X86::COND_O;
15811       break;
15812     case Intrinsic::x86_sse42_pcmpestrio128:
15813       Opcode = X86ISD::PCMPESTRI;
15814       X86CC = X86::COND_O;
15815       break;
15816     case Intrinsic::x86_sse42_pcmpistris128:
15817       Opcode = X86ISD::PCMPISTRI;
15818       X86CC = X86::COND_S;
15819       break;
15820     case Intrinsic::x86_sse42_pcmpestris128:
15821       Opcode = X86ISD::PCMPESTRI;
15822       X86CC = X86::COND_S;
15823       break;
15824     case Intrinsic::x86_sse42_pcmpistriz128:
15825       Opcode = X86ISD::PCMPISTRI;
15826       X86CC = X86::COND_E;
15827       break;
15828     case Intrinsic::x86_sse42_pcmpestriz128:
15829       Opcode = X86ISD::PCMPESTRI;
15830       X86CC = X86::COND_E;
15831       break;
15832     }
15833     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15834     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15835     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15836     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15837                                 DAG.getConstant(X86CC, dl, MVT::i8),
15838                                 SDValue(PCMP.getNode(), 1));
15839     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15840   }
15841
15842   case Intrinsic::x86_sse42_pcmpistri128:
15843   case Intrinsic::x86_sse42_pcmpestri128: {
15844     unsigned Opcode;
15845     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15846       Opcode = X86ISD::PCMPISTRI;
15847     else
15848       Opcode = X86ISD::PCMPESTRI;
15849
15850     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15851     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15852     return DAG.getNode(Opcode, dl, VTs, NewOps);
15853   }
15854
15855   case Intrinsic::x86_seh_lsda: {
15856     // Compute the symbol for the LSDA. We know it'll get emitted later.
15857     MachineFunction &MF = DAG.getMachineFunction();
15858     SDValue Op1 = Op.getOperand(1);
15859     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15860     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15861         GlobalValue::getRealLinkageName(Fn->getName()));
15862
15863     // Generate a simple absolute symbol reference. This intrinsic is only
15864     // supported on 32-bit Windows, which isn't PIC.
15865     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15866     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15867   }
15868
15869   case Intrinsic::x86_seh_recoverfp: {
15870     SDValue FnOp = Op.getOperand(1);
15871     SDValue IncomingFPOp = Op.getOperand(2);
15872     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15873     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15874     if (!Fn)
15875       report_fatal_error(
15876           "llvm.x86.seh.recoverfp must take a function as the first argument");
15877     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15878   }
15879
15880   case Intrinsic::localaddress: {
15881     // Returns one of the stack, base, or frame pointer registers, depending on
15882     // which is used to reference local variables.
15883     MachineFunction &MF = DAG.getMachineFunction();
15884     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15885     unsigned Reg;
15886     if (RegInfo->hasBasePointer(MF))
15887       Reg = RegInfo->getBaseRegister();
15888     else // This function handles the SP or FP case.
15889       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15890     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15891   }
15892   }
15893 }
15894
15895 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15896                               SDValue Src, SDValue Mask, SDValue Base,
15897                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15898                               const X86Subtarget * Subtarget) {
15899   SDLoc dl(Op);
15900   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15901   if (!C)
15902     llvm_unreachable("Invalid scale type");
15903   unsigned ScaleVal = C->getZExtValue();
15904   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15905     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15906
15907   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15908   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15909                              Index.getSimpleValueType().getVectorNumElements());
15910   SDValue MaskInReg;
15911   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15912   if (MaskC)
15913     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15914   else {
15915     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15916                                      Mask.getValueType().getSizeInBits());
15917
15918     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15919     // are extracted by EXTRACT_SUBVECTOR.
15920     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15921                             DAG.getBitcast(BitcastVT, Mask),
15922                             DAG.getIntPtrConstant(0, dl));
15923   }
15924   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15925   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15926   SDValue Segment = DAG.getRegister(0, MVT::i32);
15927   if (Src.getOpcode() == ISD::UNDEF)
15928     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15929   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15930   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15931   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15932   return DAG.getMergeValues(RetOps, dl);
15933 }
15934
15935 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15936                                SDValue Src, SDValue Mask, SDValue Base,
15937                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15938   SDLoc dl(Op);
15939   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15940   if (!C)
15941     llvm_unreachable("Invalid scale type");
15942   unsigned ScaleVal = C->getZExtValue();
15943   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15944     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15945
15946   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15947   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15948   SDValue Segment = DAG.getRegister(0, MVT::i32);
15949   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15950                              Index.getSimpleValueType().getVectorNumElements());
15951   SDValue MaskInReg;
15952   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15953   if (MaskC)
15954     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15955   else {
15956     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15957                                      Mask.getValueType().getSizeInBits());
15958
15959     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15960     // are extracted by EXTRACT_SUBVECTOR.
15961     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15962                             DAG.getBitcast(BitcastVT, Mask),
15963                             DAG.getIntPtrConstant(0, dl));
15964   }
15965   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15966   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15967   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15968   return SDValue(Res, 1);
15969 }
15970
15971 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15972                                SDValue Mask, SDValue Base, SDValue Index,
15973                                SDValue ScaleOp, SDValue Chain) {
15974   SDLoc dl(Op);
15975   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15976   assert(C && "Invalid scale type");
15977   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15978   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15979   SDValue Segment = DAG.getRegister(0, MVT::i32);
15980   EVT MaskVT =
15981     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15982   SDValue MaskInReg;
15983   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15984   if (MaskC)
15985     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15986   else
15987     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15988   //SDVTList VTs = DAG.getVTList(MVT::Other);
15989   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15990   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15991   return SDValue(Res, 0);
15992 }
15993
15994 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15995 // read performance monitor counters (x86_rdpmc).
15996 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15997                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15998                               SmallVectorImpl<SDValue> &Results) {
15999   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16000   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16001   SDValue LO, HI;
16002
16003   // The ECX register is used to select the index of the performance counter
16004   // to read.
16005   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16006                                    N->getOperand(2));
16007   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16008
16009   // Reads the content of a 64-bit performance counter and returns it in the
16010   // registers EDX:EAX.
16011   if (Subtarget->is64Bit()) {
16012     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16013     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16014                             LO.getValue(2));
16015   } else {
16016     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16017     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16018                             LO.getValue(2));
16019   }
16020   Chain = HI.getValue(1);
16021
16022   if (Subtarget->is64Bit()) {
16023     // The EAX register is loaded with the low-order 32 bits. The EDX register
16024     // is loaded with the supported high-order bits of the counter.
16025     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16026                               DAG.getConstant(32, DL, MVT::i8));
16027     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16028     Results.push_back(Chain);
16029     return;
16030   }
16031
16032   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16033   SDValue Ops[] = { LO, HI };
16034   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16035   Results.push_back(Pair);
16036   Results.push_back(Chain);
16037 }
16038
16039 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16040 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16041 // also used to custom lower READCYCLECOUNTER nodes.
16042 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16043                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16044                               SmallVectorImpl<SDValue> &Results) {
16045   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16046   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16047   SDValue LO, HI;
16048
16049   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16050   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16051   // and the EAX register is loaded with the low-order 32 bits.
16052   if (Subtarget->is64Bit()) {
16053     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16054     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16055                             LO.getValue(2));
16056   } else {
16057     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16058     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16059                             LO.getValue(2));
16060   }
16061   SDValue Chain = HI.getValue(1);
16062
16063   if (Opcode == X86ISD::RDTSCP_DAG) {
16064     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16065
16066     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16067     // the ECX register. Add 'ecx' explicitly to the chain.
16068     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16069                                      HI.getValue(2));
16070     // Explicitly store the content of ECX at the location passed in input
16071     // to the 'rdtscp' intrinsic.
16072     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16073                          MachinePointerInfo(), false, false, 0);
16074   }
16075
16076   if (Subtarget->is64Bit()) {
16077     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16078     // the EAX register is loaded with the low-order 32 bits.
16079     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16080                               DAG.getConstant(32, DL, MVT::i8));
16081     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16082     Results.push_back(Chain);
16083     return;
16084   }
16085
16086   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16087   SDValue Ops[] = { LO, HI };
16088   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16089   Results.push_back(Pair);
16090   Results.push_back(Chain);
16091 }
16092
16093 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16094                                      SelectionDAG &DAG) {
16095   SmallVector<SDValue, 2> Results;
16096   SDLoc DL(Op);
16097   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16098                           Results);
16099   return DAG.getMergeValues(Results, DL);
16100 }
16101
16102 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16103                                     SelectionDAG &DAG) {
16104   MachineFunction &MF = DAG.getMachineFunction();
16105   const Function *Fn = MF.getFunction();
16106   SDLoc dl(Op);
16107   SDValue Chain = Op.getOperand(0);
16108
16109   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16110          "using llvm.x86.seh.restoreframe requires a frame pointer");
16111
16112   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16113   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16114
16115   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16116   unsigned FrameReg =
16117       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16118   unsigned SPReg = RegInfo->getStackRegister();
16119   unsigned SlotSize = RegInfo->getSlotSize();
16120
16121   // Get incoming EBP.
16122   SDValue IncomingEBP =
16123       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16124
16125   // SP is saved in the first field of every registration node, so load
16126   // [EBP-RegNodeSize] into SP.
16127   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16128   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16129                                DAG.getConstant(-RegNodeSize, dl, VT));
16130   SDValue NewSP =
16131       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16132                   false, VT.getScalarSizeInBits() / 8);
16133   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16134
16135   if (!RegInfo->needsStackRealignment(MF)) {
16136     // Adjust EBP to point back to the original frame position.
16137     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16138     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16139   } else {
16140     assert(RegInfo->hasBasePointer(MF) &&
16141            "functions with Win32 EH must use frame or base pointer register");
16142
16143     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16144     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16145     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16146
16147     // Reload the spilled EBP value, now that the stack and base pointers are
16148     // set up.
16149     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16150     X86FI->setHasSEHFramePtrSave(true);
16151     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16152     X86FI->setSEHFramePtrSaveIndex(FI);
16153     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16154                                 MachinePointerInfo(), false, false, false,
16155                                 VT.getScalarSizeInBits() / 8);
16156     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16157   }
16158
16159   return Chain;
16160 }
16161
16162 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16163 /// return truncate Store/MaskedStore Node
16164 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16165                                                SelectionDAG &DAG,
16166                                                MVT ElementType) {
16167   SDLoc dl(Op);
16168   SDValue Mask = Op.getOperand(4);
16169   SDValue DataToTruncate = Op.getOperand(3);
16170   SDValue Addr = Op.getOperand(2);
16171   SDValue Chain = Op.getOperand(0);
16172
16173   EVT VT  = DataToTruncate.getValueType();
16174   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16175                              ElementType, VT.getVectorNumElements());
16176
16177   if (isAllOnes(Mask)) // return just a truncate store
16178     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16179                              MachinePointerInfo(), SVT, false, false,
16180                              SVT.getScalarSizeInBits()/8);
16181
16182   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16183                                 MVT::i1, VT.getVectorNumElements());
16184   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16185                                    Mask.getValueType().getSizeInBits());
16186   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16187   // are extracted by EXTRACT_SUBVECTOR.
16188   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16189                               DAG.getBitcast(BitcastVT, Mask),
16190                               DAG.getIntPtrConstant(0, dl));
16191
16192   MachineMemOperand *MMO = DAG.getMachineFunction().
16193     getMachineMemOperand(MachinePointerInfo(),
16194                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16195                          SVT.getScalarSizeInBits()/8);
16196
16197   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16198                             VMask, SVT, MMO, true);
16199 }
16200
16201 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16202                                       SelectionDAG &DAG) {
16203   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16204
16205   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16206   if (!IntrData) {
16207     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16208       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16209     return SDValue();
16210   }
16211
16212   SDLoc dl(Op);
16213   switch(IntrData->Type) {
16214   default:
16215     llvm_unreachable("Unknown Intrinsic Type");
16216     break;
16217   case RDSEED:
16218   case RDRAND: {
16219     // Emit the node with the right value type.
16220     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16221     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16222
16223     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16224     // Otherwise return the value from Rand, which is always 0, casted to i32.
16225     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16226                       DAG.getConstant(1, dl, Op->getValueType(1)),
16227                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16228                       SDValue(Result.getNode(), 1) };
16229     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16230                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16231                                   Ops);
16232
16233     // Return { result, isValid, chain }.
16234     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16235                        SDValue(Result.getNode(), 2));
16236   }
16237   case GATHER: {
16238   //gather(v1, mask, index, base, scale);
16239     SDValue Chain = Op.getOperand(0);
16240     SDValue Src   = Op.getOperand(2);
16241     SDValue Base  = Op.getOperand(3);
16242     SDValue Index = Op.getOperand(4);
16243     SDValue Mask  = Op.getOperand(5);
16244     SDValue Scale = Op.getOperand(6);
16245     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16246                          Chain, Subtarget);
16247   }
16248   case SCATTER: {
16249   //scatter(base, mask, index, v1, scale);
16250     SDValue Chain = Op.getOperand(0);
16251     SDValue Base  = Op.getOperand(2);
16252     SDValue Mask  = Op.getOperand(3);
16253     SDValue Index = Op.getOperand(4);
16254     SDValue Src   = Op.getOperand(5);
16255     SDValue Scale = Op.getOperand(6);
16256     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16257                           Scale, Chain);
16258   }
16259   case PREFETCH: {
16260     SDValue Hint = Op.getOperand(6);
16261     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16262     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16263     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16264     SDValue Chain = Op.getOperand(0);
16265     SDValue Mask  = Op.getOperand(2);
16266     SDValue Index = Op.getOperand(3);
16267     SDValue Base  = Op.getOperand(4);
16268     SDValue Scale = Op.getOperand(5);
16269     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16270   }
16271   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16272   case RDTSC: {
16273     SmallVector<SDValue, 2> Results;
16274     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16275                             Results);
16276     return DAG.getMergeValues(Results, dl);
16277   }
16278   // Read Performance Monitoring Counters.
16279   case RDPMC: {
16280     SmallVector<SDValue, 2> Results;
16281     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16282     return DAG.getMergeValues(Results, dl);
16283   }
16284   // XTEST intrinsics.
16285   case XTEST: {
16286     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16287     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16288     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16289                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16290                                 InTrans);
16291     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16292     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16293                        Ret, SDValue(InTrans.getNode(), 1));
16294   }
16295   // ADC/ADCX/SBB
16296   case ADX: {
16297     SmallVector<SDValue, 2> Results;
16298     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16299     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16300     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16301                                 DAG.getConstant(-1, dl, MVT::i8));
16302     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16303                               Op.getOperand(4), GenCF.getValue(1));
16304     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16305                                  Op.getOperand(5), MachinePointerInfo(),
16306                                  false, false, 0);
16307     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16308                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16309                                 Res.getValue(1));
16310     Results.push_back(SetCC);
16311     Results.push_back(Store);
16312     return DAG.getMergeValues(Results, dl);
16313   }
16314   case COMPRESS_TO_MEM: {
16315     SDLoc dl(Op);
16316     SDValue Mask = Op.getOperand(4);
16317     SDValue DataToCompress = Op.getOperand(3);
16318     SDValue Addr = Op.getOperand(2);
16319     SDValue Chain = Op.getOperand(0);
16320
16321     EVT VT = DataToCompress.getValueType();
16322     if (isAllOnes(Mask)) // return just a store
16323       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16324                           MachinePointerInfo(), false, false,
16325                           VT.getScalarSizeInBits()/8);
16326
16327     SDValue Compressed =
16328       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16329                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16330     return DAG.getStore(Chain, dl, Compressed, Addr,
16331                         MachinePointerInfo(), false, false,
16332                         VT.getScalarSizeInBits()/8);
16333   }
16334   case TRUNCATE_TO_MEM_VI8:
16335     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16336   case TRUNCATE_TO_MEM_VI16:
16337     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16338   case TRUNCATE_TO_MEM_VI32:
16339     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16340   case EXPAND_FROM_MEM: {
16341     SDLoc dl(Op);
16342     SDValue Mask = Op.getOperand(4);
16343     SDValue PassThru = Op.getOperand(3);
16344     SDValue Addr = Op.getOperand(2);
16345     SDValue Chain = Op.getOperand(0);
16346     EVT VT = Op.getValueType();
16347
16348     if (isAllOnes(Mask)) // return just a load
16349       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16350                          false, VT.getScalarSizeInBits()/8);
16351
16352     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16353                                        false, false, false,
16354                                        VT.getScalarSizeInBits()/8);
16355
16356     SDValue Results[] = {
16357       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16358                            Mask, PassThru, Subtarget, DAG), Chain};
16359     return DAG.getMergeValues(Results, dl);
16360   }
16361   }
16362 }
16363
16364 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16365                                            SelectionDAG &DAG) const {
16366   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16367   MFI->setReturnAddressIsTaken(true);
16368
16369   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16370     return SDValue();
16371
16372   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16373   SDLoc dl(Op);
16374   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16375
16376   if (Depth > 0) {
16377     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16378     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16379     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16380     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16381                        DAG.getNode(ISD::ADD, dl, PtrVT,
16382                                    FrameAddr, Offset),
16383                        MachinePointerInfo(), false, false, false, 0);
16384   }
16385
16386   // Just load the return address.
16387   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16388   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16389                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16390 }
16391
16392 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16393   MachineFunction &MF = DAG.getMachineFunction();
16394   MachineFrameInfo *MFI = MF.getFrameInfo();
16395   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16396   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16397   EVT VT = Op.getValueType();
16398
16399   MFI->setFrameAddressIsTaken(true);
16400
16401   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16402     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16403     // is not possible to crawl up the stack without looking at the unwind codes
16404     // simultaneously.
16405     int FrameAddrIndex = FuncInfo->getFAIndex();
16406     if (!FrameAddrIndex) {
16407       // Set up a frame object for the return address.
16408       unsigned SlotSize = RegInfo->getSlotSize();
16409       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16410           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16411       FuncInfo->setFAIndex(FrameAddrIndex);
16412     }
16413     return DAG.getFrameIndex(FrameAddrIndex, VT);
16414   }
16415
16416   unsigned FrameReg =
16417       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16418   SDLoc dl(Op);  // FIXME probably not meaningful
16419   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16420   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16421           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16422          "Invalid Frame Register!");
16423   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16424   while (Depth--)
16425     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16426                             MachinePointerInfo(),
16427                             false, false, false, 0);
16428   return FrameAddr;
16429 }
16430
16431 // FIXME? Maybe this could be a TableGen attribute on some registers and
16432 // this table could be generated automatically from RegInfo.
16433 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16434                                               SelectionDAG &DAG) const {
16435   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16436   const MachineFunction &MF = DAG.getMachineFunction();
16437
16438   unsigned Reg = StringSwitch<unsigned>(RegName)
16439                        .Case("esp", X86::ESP)
16440                        .Case("rsp", X86::RSP)
16441                        .Case("ebp", X86::EBP)
16442                        .Case("rbp", X86::RBP)
16443                        .Default(0);
16444
16445   if (Reg == X86::EBP || Reg == X86::RBP) {
16446     if (!TFI.hasFP(MF))
16447       report_fatal_error("register " + StringRef(RegName) +
16448                          " is allocatable: function has no frame pointer");
16449 #ifndef NDEBUG
16450     else {
16451       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16452       unsigned FrameReg =
16453           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16454       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16455              "Invalid Frame Register!");
16456     }
16457 #endif
16458   }
16459
16460   if (Reg)
16461     return Reg;
16462
16463   report_fatal_error("Invalid register name global variable");
16464 }
16465
16466 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16467                                                      SelectionDAG &DAG) const {
16468   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16469   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16470 }
16471
16472 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16473   SDValue Chain     = Op.getOperand(0);
16474   SDValue Offset    = Op.getOperand(1);
16475   SDValue Handler   = Op.getOperand(2);
16476   SDLoc dl      (Op);
16477
16478   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16479   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16480   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16481   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16482           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16483          "Invalid Frame Register!");
16484   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16485   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16486
16487   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16488                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16489                                                        dl));
16490   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16491   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16492                        false, false, 0);
16493   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16494
16495   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16496                      DAG.getRegister(StoreAddrReg, PtrVT));
16497 }
16498
16499 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16500                                                SelectionDAG &DAG) const {
16501   SDLoc DL(Op);
16502   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16503                      DAG.getVTList(MVT::i32, MVT::Other),
16504                      Op.getOperand(0), Op.getOperand(1));
16505 }
16506
16507 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16508                                                 SelectionDAG &DAG) const {
16509   SDLoc DL(Op);
16510   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16511                      Op.getOperand(0), Op.getOperand(1));
16512 }
16513
16514 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16515   return Op.getOperand(0);
16516 }
16517
16518 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16519                                                 SelectionDAG &DAG) const {
16520   SDValue Root = Op.getOperand(0);
16521   SDValue Trmp = Op.getOperand(1); // trampoline
16522   SDValue FPtr = Op.getOperand(2); // nested function
16523   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16524   SDLoc dl (Op);
16525
16526   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16527   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16528
16529   if (Subtarget->is64Bit()) {
16530     SDValue OutChains[6];
16531
16532     // Large code-model.
16533     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16534     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16535
16536     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16537     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16538
16539     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16540
16541     // Load the pointer to the nested function into R11.
16542     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16543     SDValue Addr = Trmp;
16544     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16545                                 Addr, MachinePointerInfo(TrmpAddr),
16546                                 false, false, 0);
16547
16548     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16549                        DAG.getConstant(2, dl, MVT::i64));
16550     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16551                                 MachinePointerInfo(TrmpAddr, 2),
16552                                 false, false, 2);
16553
16554     // Load the 'nest' parameter value into R10.
16555     // R10 is specified in X86CallingConv.td
16556     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16557     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16558                        DAG.getConstant(10, dl, MVT::i64));
16559     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16560                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16561                                 false, false, 0);
16562
16563     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16564                        DAG.getConstant(12, dl, MVT::i64));
16565     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16566                                 MachinePointerInfo(TrmpAddr, 12),
16567                                 false, false, 2);
16568
16569     // Jump to the nested function.
16570     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16571     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16572                        DAG.getConstant(20, dl, MVT::i64));
16573     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16574                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16575                                 false, false, 0);
16576
16577     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16578     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16579                        DAG.getConstant(22, dl, MVT::i64));
16580     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16581                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16582                                 false, false, 0);
16583
16584     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16585   } else {
16586     const Function *Func =
16587       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16588     CallingConv::ID CC = Func->getCallingConv();
16589     unsigned NestReg;
16590
16591     switch (CC) {
16592     default:
16593       llvm_unreachable("Unsupported calling convention");
16594     case CallingConv::C:
16595     case CallingConv::X86_StdCall: {
16596       // Pass 'nest' parameter in ECX.
16597       // Must be kept in sync with X86CallingConv.td
16598       NestReg = X86::ECX;
16599
16600       // Check that ECX wasn't needed by an 'inreg' parameter.
16601       FunctionType *FTy = Func->getFunctionType();
16602       const AttributeSet &Attrs = Func->getAttributes();
16603
16604       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16605         unsigned InRegCount = 0;
16606         unsigned Idx = 1;
16607
16608         for (FunctionType::param_iterator I = FTy->param_begin(),
16609              E = FTy->param_end(); I != E; ++I, ++Idx)
16610           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16611             auto &DL = DAG.getDataLayout();
16612             // FIXME: should only count parameters that are lowered to integers.
16613             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16614           }
16615
16616         if (InRegCount > 2) {
16617           report_fatal_error("Nest register in use - reduce number of inreg"
16618                              " parameters!");
16619         }
16620       }
16621       break;
16622     }
16623     case CallingConv::X86_FastCall:
16624     case CallingConv::X86_ThisCall:
16625     case CallingConv::Fast:
16626       // Pass 'nest' parameter in EAX.
16627       // Must be kept in sync with X86CallingConv.td
16628       NestReg = X86::EAX;
16629       break;
16630     }
16631
16632     SDValue OutChains[4];
16633     SDValue Addr, Disp;
16634
16635     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16636                        DAG.getConstant(10, dl, MVT::i32));
16637     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16638
16639     // This is storing the opcode for MOV32ri.
16640     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16641     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16642     OutChains[0] = DAG.getStore(Root, dl,
16643                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16644                                 Trmp, MachinePointerInfo(TrmpAddr),
16645                                 false, false, 0);
16646
16647     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16648                        DAG.getConstant(1, dl, MVT::i32));
16649     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16650                                 MachinePointerInfo(TrmpAddr, 1),
16651                                 false, false, 1);
16652
16653     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16654     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16655                        DAG.getConstant(5, dl, MVT::i32));
16656     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16657                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16658                                 false, false, 1);
16659
16660     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16661                        DAG.getConstant(6, dl, MVT::i32));
16662     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16663                                 MachinePointerInfo(TrmpAddr, 6),
16664                                 false, false, 1);
16665
16666     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16667   }
16668 }
16669
16670 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16671                                             SelectionDAG &DAG) const {
16672   /*
16673    The rounding mode is in bits 11:10 of FPSR, and has the following
16674    settings:
16675      00 Round to nearest
16676      01 Round to -inf
16677      10 Round to +inf
16678      11 Round to 0
16679
16680   FLT_ROUNDS, on the other hand, expects the following:
16681     -1 Undefined
16682      0 Round to 0
16683      1 Round to nearest
16684      2 Round to +inf
16685      3 Round to -inf
16686
16687   To perform the conversion, we do:
16688     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16689   */
16690
16691   MachineFunction &MF = DAG.getMachineFunction();
16692   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16693   unsigned StackAlignment = TFI.getStackAlignment();
16694   MVT VT = Op.getSimpleValueType();
16695   SDLoc DL(Op);
16696
16697   // Save FP Control Word to stack slot
16698   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16699   SDValue StackSlot =
16700       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16701
16702   MachineMemOperand *MMO =
16703    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16704                            MachineMemOperand::MOStore, 2, 2);
16705
16706   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16707   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16708                                           DAG.getVTList(MVT::Other),
16709                                           Ops, MVT::i16, MMO);
16710
16711   // Load FP Control Word from stack slot
16712   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16713                             MachinePointerInfo(), false, false, false, 0);
16714
16715   // Transform as necessary
16716   SDValue CWD1 =
16717     DAG.getNode(ISD::SRL, DL, MVT::i16,
16718                 DAG.getNode(ISD::AND, DL, MVT::i16,
16719                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16720                 DAG.getConstant(11, DL, MVT::i8));
16721   SDValue CWD2 =
16722     DAG.getNode(ISD::SRL, DL, MVT::i16,
16723                 DAG.getNode(ISD::AND, DL, MVT::i16,
16724                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16725                 DAG.getConstant(9, DL, MVT::i8));
16726
16727   SDValue RetVal =
16728     DAG.getNode(ISD::AND, DL, MVT::i16,
16729                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16730                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16731                             DAG.getConstant(1, DL, MVT::i16)),
16732                 DAG.getConstant(3, DL, MVT::i16));
16733
16734   return DAG.getNode((VT.getSizeInBits() < 16 ?
16735                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16736 }
16737
16738 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16739   MVT VT = Op.getSimpleValueType();
16740   EVT OpVT = VT;
16741   unsigned NumBits = VT.getSizeInBits();
16742   SDLoc dl(Op);
16743
16744   Op = Op.getOperand(0);
16745   if (VT == MVT::i8) {
16746     // Zero extend to i32 since there is not an i8 bsr.
16747     OpVT = MVT::i32;
16748     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16749   }
16750
16751   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16752   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16753   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16754
16755   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16756   SDValue Ops[] = {
16757     Op,
16758     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16759     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16760     Op.getValue(1)
16761   };
16762   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16763
16764   // Finally xor with NumBits-1.
16765   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16766                    DAG.getConstant(NumBits - 1, dl, OpVT));
16767
16768   if (VT == MVT::i8)
16769     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16770   return Op;
16771 }
16772
16773 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16774   MVT VT = Op.getSimpleValueType();
16775   EVT OpVT = VT;
16776   unsigned NumBits = VT.getSizeInBits();
16777   SDLoc dl(Op);
16778
16779   Op = Op.getOperand(0);
16780   if (VT == MVT::i8) {
16781     // Zero extend to i32 since there is not an i8 bsr.
16782     OpVT = MVT::i32;
16783     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16784   }
16785
16786   // Issue a bsr (scan bits in reverse).
16787   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16788   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16789
16790   // And xor with NumBits-1.
16791   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16792                    DAG.getConstant(NumBits - 1, dl, OpVT));
16793
16794   if (VT == MVT::i8)
16795     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16796   return Op;
16797 }
16798
16799 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16800   MVT VT = Op.getSimpleValueType();
16801   unsigned NumBits = VT.getSizeInBits();
16802   SDLoc dl(Op);
16803   Op = Op.getOperand(0);
16804
16805   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16806   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16807   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16808
16809   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16810   SDValue Ops[] = {
16811     Op,
16812     DAG.getConstant(NumBits, dl, VT),
16813     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16814     Op.getValue(1)
16815   };
16816   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16817 }
16818
16819 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16820 // ones, and then concatenate the result back.
16821 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16822   MVT VT = Op.getSimpleValueType();
16823
16824   assert(VT.is256BitVector() && VT.isInteger() &&
16825          "Unsupported value type for operation");
16826
16827   unsigned NumElems = VT.getVectorNumElements();
16828   SDLoc dl(Op);
16829
16830   // Extract the LHS vectors
16831   SDValue LHS = Op.getOperand(0);
16832   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16833   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16834
16835   // Extract the RHS vectors
16836   SDValue RHS = Op.getOperand(1);
16837   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16838   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16839
16840   MVT EltVT = VT.getVectorElementType();
16841   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16842
16843   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16844                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16845                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16846 }
16847
16848 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16849   if (Op.getValueType() == MVT::i1)
16850     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16851                        Op.getOperand(0), Op.getOperand(1));
16852   assert(Op.getSimpleValueType().is256BitVector() &&
16853          Op.getSimpleValueType().isInteger() &&
16854          "Only handle AVX 256-bit vector integer operation");
16855   return Lower256IntArith(Op, DAG);
16856 }
16857
16858 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16859   if (Op.getValueType() == MVT::i1)
16860     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16861                        Op.getOperand(0), Op.getOperand(1));
16862   assert(Op.getSimpleValueType().is256BitVector() &&
16863          Op.getSimpleValueType().isInteger() &&
16864          "Only handle AVX 256-bit vector integer operation");
16865   return Lower256IntArith(Op, DAG);
16866 }
16867
16868 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16869                         SelectionDAG &DAG) {
16870   SDLoc dl(Op);
16871   MVT VT = Op.getSimpleValueType();
16872
16873   if (VT == MVT::i1)
16874     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16875
16876   // Decompose 256-bit ops into smaller 128-bit ops.
16877   if (VT.is256BitVector() && !Subtarget->hasInt256())
16878     return Lower256IntArith(Op, DAG);
16879
16880   SDValue A = Op.getOperand(0);
16881   SDValue B = Op.getOperand(1);
16882
16883   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16884   // pairs, multiply and truncate.
16885   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16886     if (Subtarget->hasInt256()) {
16887       if (VT == MVT::v32i8) {
16888         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16889         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16890         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16891         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16892         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16893         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16894         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16895         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16896                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16897                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16898       }
16899
16900       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16901       return DAG.getNode(
16902           ISD::TRUNCATE, dl, VT,
16903           DAG.getNode(ISD::MUL, dl, ExVT,
16904                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16905                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16906     }
16907
16908     assert(VT == MVT::v16i8 &&
16909            "Pre-AVX2 support only supports v16i8 multiplication");
16910     MVT ExVT = MVT::v8i16;
16911
16912     // Extract the lo parts and sign extend to i16
16913     SDValue ALo, BLo;
16914     if (Subtarget->hasSSE41()) {
16915       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16916       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16917     } else {
16918       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16919                               -1, 4, -1, 5, -1, 6, -1, 7};
16920       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16921       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16922       ALo = DAG.getBitcast(ExVT, ALo);
16923       BLo = DAG.getBitcast(ExVT, BLo);
16924       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16925       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16926     }
16927
16928     // Extract the hi parts and sign extend to i16
16929     SDValue AHi, BHi;
16930     if (Subtarget->hasSSE41()) {
16931       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16932                               -1, -1, -1, -1, -1, -1, -1, -1};
16933       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16934       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16935       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16936       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16937     } else {
16938       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16939                               -1, 12, -1, 13, -1, 14, -1, 15};
16940       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16941       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16942       AHi = DAG.getBitcast(ExVT, AHi);
16943       BHi = DAG.getBitcast(ExVT, BHi);
16944       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16945       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16946     }
16947
16948     // Multiply, mask the lower 8bits of the lo/hi results and pack
16949     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16950     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16951     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16952     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16953     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16954   }
16955
16956   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16957   if (VT == MVT::v4i32) {
16958     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16959            "Should not custom lower when pmuldq is available!");
16960
16961     // Extract the odd parts.
16962     static const int UnpackMask[] = { 1, -1, 3, -1 };
16963     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16964     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16965
16966     // Multiply the even parts.
16967     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16968     // Now multiply odd parts.
16969     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16970
16971     Evens = DAG.getBitcast(VT, Evens);
16972     Odds = DAG.getBitcast(VT, Odds);
16973
16974     // Merge the two vectors back together with a shuffle. This expands into 2
16975     // shuffles.
16976     static const int ShufMask[] = { 0, 4, 2, 6 };
16977     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16978   }
16979
16980   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16981          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16982
16983   //  Ahi = psrlqi(a, 32);
16984   //  Bhi = psrlqi(b, 32);
16985   //
16986   //  AloBlo = pmuludq(a, b);
16987   //  AloBhi = pmuludq(a, Bhi);
16988   //  AhiBlo = pmuludq(Ahi, b);
16989
16990   //  AloBhi = psllqi(AloBhi, 32);
16991   //  AhiBlo = psllqi(AhiBlo, 32);
16992   //  return AloBlo + AloBhi + AhiBlo;
16993
16994   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16995   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16996
16997   SDValue AhiBlo = Ahi;
16998   SDValue AloBhi = Bhi;
16999   // Bit cast to 32-bit vectors for MULUDQ
17000   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17001                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17002   A = DAG.getBitcast(MulVT, A);
17003   B = DAG.getBitcast(MulVT, B);
17004   Ahi = DAG.getBitcast(MulVT, Ahi);
17005   Bhi = DAG.getBitcast(MulVT, Bhi);
17006
17007   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17008   // After shifting right const values the result may be all-zero.
17009   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17010     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17011     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17012   }
17013   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17014     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17015     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17016   }
17017
17018   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17019   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17020 }
17021
17022 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17023   assert(Subtarget->isTargetWin64() && "Unexpected target");
17024   EVT VT = Op.getValueType();
17025   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17026          "Unexpected return type for lowering");
17027
17028   RTLIB::Libcall LC;
17029   bool isSigned;
17030   switch (Op->getOpcode()) {
17031   default: llvm_unreachable("Unexpected request for libcall!");
17032   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17033   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17034   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17035   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17036   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17037   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17038   }
17039
17040   SDLoc dl(Op);
17041   SDValue InChain = DAG.getEntryNode();
17042
17043   TargetLowering::ArgListTy Args;
17044   TargetLowering::ArgListEntry Entry;
17045   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17046     EVT ArgVT = Op->getOperand(i).getValueType();
17047     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17048            "Unexpected argument type for lowering");
17049     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17050     Entry.Node = StackPtr;
17051     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17052                            false, false, 16);
17053     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17054     Entry.Ty = PointerType::get(ArgTy,0);
17055     Entry.isSExt = false;
17056     Entry.isZExt = false;
17057     Args.push_back(Entry);
17058   }
17059
17060   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17061                                          getPointerTy(DAG.getDataLayout()));
17062
17063   TargetLowering::CallLoweringInfo CLI(DAG);
17064   CLI.setDebugLoc(dl).setChain(InChain)
17065     .setCallee(getLibcallCallingConv(LC),
17066                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17067                Callee, std::move(Args), 0)
17068     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17069
17070   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17071   return DAG.getBitcast(VT, CallInfo.first);
17072 }
17073
17074 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17075                              SelectionDAG &DAG) {
17076   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17077   EVT VT = Op0.getValueType();
17078   SDLoc dl(Op);
17079
17080   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17081          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17082
17083   // PMULxD operations multiply each even value (starting at 0) of LHS with
17084   // the related value of RHS and produce a widen result.
17085   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17086   // => <2 x i64> <ae|cg>
17087   //
17088   // In other word, to have all the results, we need to perform two PMULxD:
17089   // 1. one with the even values.
17090   // 2. one with the odd values.
17091   // To achieve #2, with need to place the odd values at an even position.
17092   //
17093   // Place the odd value at an even position (basically, shift all values 1
17094   // step to the left):
17095   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17096   // <a|b|c|d> => <b|undef|d|undef>
17097   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17098   // <e|f|g|h> => <f|undef|h|undef>
17099   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17100
17101   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17102   // ints.
17103   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17104   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17105   unsigned Opcode =
17106       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17107   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17108   // => <2 x i64> <ae|cg>
17109   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17110   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17111   // => <2 x i64> <bf|dh>
17112   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17113
17114   // Shuffle it back into the right order.
17115   SDValue Highs, Lows;
17116   if (VT == MVT::v8i32) {
17117     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17118     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17119     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17120     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17121   } else {
17122     const int HighMask[] = {1, 5, 3, 7};
17123     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17124     const int LowMask[] = {0, 4, 2, 6};
17125     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17126   }
17127
17128   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17129   // unsigned multiply.
17130   if (IsSigned && !Subtarget->hasSSE41()) {
17131     SDValue ShAmt = DAG.getConstant(
17132         31, dl,
17133         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17134     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17135                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17136     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17137                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17138
17139     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17140     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17141   }
17142
17143   // The first result of MUL_LOHI is actually the low value, followed by the
17144   // high value.
17145   SDValue Ops[] = {Lows, Highs};
17146   return DAG.getMergeValues(Ops, dl);
17147 }
17148
17149 // Return true if the required (according to Opcode) shift-imm form is natively
17150 // supported by the Subtarget
17151 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17152                                         unsigned Opcode) {
17153   if (VT.getScalarSizeInBits() < 16)
17154     return false;
17155
17156   if (VT.is512BitVector() &&
17157       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17158     return true;
17159
17160   bool LShift = VT.is128BitVector() ||
17161     (VT.is256BitVector() && Subtarget->hasInt256());
17162
17163   bool AShift = LShift && (Subtarget->hasVLX() ||
17164     (VT != MVT::v2i64 && VT != MVT::v4i64));
17165   return (Opcode == ISD::SRA) ? AShift : LShift;
17166 }
17167
17168 // The shift amount is a variable, but it is the same for all vector lanes.
17169 // These instructions are defined together with shift-immediate.
17170 static
17171 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17172                                       unsigned Opcode) {
17173   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17174 }
17175
17176 // Return true if the required (according to Opcode) variable-shift form is
17177 // natively supported by the Subtarget
17178 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17179                                     unsigned Opcode) {
17180
17181   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17182     return false;
17183
17184   // vXi16 supported only on AVX-512, BWI
17185   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17186     return false;
17187
17188   if (VT.is512BitVector() || Subtarget->hasVLX())
17189     return true;
17190
17191   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17192   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17193   return (Opcode == ISD::SRA) ? AShift : LShift;
17194 }
17195
17196 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17197                                          const X86Subtarget *Subtarget) {
17198   MVT VT = Op.getSimpleValueType();
17199   SDLoc dl(Op);
17200   SDValue R = Op.getOperand(0);
17201   SDValue Amt = Op.getOperand(1);
17202
17203   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17204     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17205
17206   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17207     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17208     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17209     SDValue Ex = DAG.getBitcast(ExVT, R);
17210
17211     if (ShiftAmt >= 32) {
17212       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17213       SDValue Upper =
17214           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17215       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17216                                                  ShiftAmt - 32, DAG);
17217       if (VT == MVT::v2i64)
17218         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17219       if (VT == MVT::v4i64)
17220         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17221                                   {9, 1, 11, 3, 13, 5, 15, 7});
17222     } else {
17223       // SRA upper i32, SHL whole i64 and select lower i32.
17224       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17225                                                  ShiftAmt, DAG);
17226       SDValue Lower =
17227           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17228       Lower = DAG.getBitcast(ExVT, Lower);
17229       if (VT == MVT::v2i64)
17230         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17231       if (VT == MVT::v4i64)
17232         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17233                                   {8, 1, 10, 3, 12, 5, 14, 7});
17234     }
17235     return DAG.getBitcast(VT, Ex);
17236   };
17237
17238   // Optimize shl/srl/sra with constant shift amount.
17239   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17240     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17241       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17242
17243       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17244         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17245
17246       // i64 SRA needs to be performed as partial shifts.
17247       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17248           Op.getOpcode() == ISD::SRA)
17249         return ArithmeticShiftRight64(ShiftAmt);
17250
17251       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17252         unsigned NumElts = VT.getVectorNumElements();
17253         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17254
17255         if (Op.getOpcode() == ISD::SHL) {
17256           // Simple i8 add case
17257           if (ShiftAmt == 1)
17258             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17259
17260           // Make a large shift.
17261           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17262                                                    R, ShiftAmt, DAG);
17263           SHL = DAG.getBitcast(VT, SHL);
17264           // Zero out the rightmost bits.
17265           SmallVector<SDValue, 32> V(
17266               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17267           return DAG.getNode(ISD::AND, dl, VT, SHL,
17268                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17269         }
17270         if (Op.getOpcode() == ISD::SRL) {
17271           // Make a large shift.
17272           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17273                                                    R, ShiftAmt, DAG);
17274           SRL = DAG.getBitcast(VT, SRL);
17275           // Zero out the leftmost bits.
17276           SmallVector<SDValue, 32> V(
17277               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17278           return DAG.getNode(ISD::AND, dl, VT, SRL,
17279                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17280         }
17281         if (Op.getOpcode() == ISD::SRA) {
17282           if (ShiftAmt == 7) {
17283             // ashr(R, 7)  === cmp_slt(R, 0)
17284             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17285             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17286           }
17287
17288           // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17289           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17290           SmallVector<SDValue, 32> V(NumElts,
17291                                      DAG.getConstant(128 >> ShiftAmt, dl,
17292                                                      MVT::i8));
17293           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17294           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17295           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17296           return Res;
17297         }
17298         llvm_unreachable("Unknown shift opcode.");
17299       }
17300     }
17301   }
17302
17303   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17304   if (!Subtarget->is64Bit() &&
17305       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17306
17307     // Peek through any splat that was introduced for i64 shift vectorization.
17308     int SplatIndex = -1;
17309     if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17310       if (SVN->isSplat()) {
17311         SplatIndex = SVN->getSplatIndex();
17312         Amt = Amt.getOperand(0);
17313         assert(SplatIndex < (int)VT.getVectorNumElements() &&
17314                "Splat shuffle referencing second operand");
17315       }
17316
17317     if (Amt.getOpcode() != ISD::BITCAST ||
17318         Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17319       return SDValue();
17320
17321     Amt = Amt.getOperand(0);
17322     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17323                      VT.getVectorNumElements();
17324     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17325     uint64_t ShiftAmt = 0;
17326     unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17327     for (unsigned i = 0; i != Ratio; ++i) {
17328       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17329       if (!C)
17330         return SDValue();
17331       // 6 == Log2(64)
17332       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17333     }
17334
17335     // Check remaining shift amounts (if not a splat).
17336     if (SplatIndex < 0) {
17337       for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17338         uint64_t ShAmt = 0;
17339         for (unsigned j = 0; j != Ratio; ++j) {
17340           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17341           if (!C)
17342             return SDValue();
17343           // 6 == Log2(64)
17344           ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17345         }
17346         if (ShAmt != ShiftAmt)
17347           return SDValue();
17348       }
17349     }
17350
17351     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17352       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17353
17354     if (Op.getOpcode() == ISD::SRA)
17355       return ArithmeticShiftRight64(ShiftAmt);
17356   }
17357
17358   return SDValue();
17359 }
17360
17361 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17362                                         const X86Subtarget* Subtarget) {
17363   MVT VT = Op.getSimpleValueType();
17364   SDLoc dl(Op);
17365   SDValue R = Op.getOperand(0);
17366   SDValue Amt = Op.getOperand(1);
17367
17368   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17369     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17370
17371   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17372     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17373
17374   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17375     SDValue BaseShAmt;
17376     EVT EltVT = VT.getVectorElementType();
17377
17378     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17379       // Check if this build_vector node is doing a splat.
17380       // If so, then set BaseShAmt equal to the splat value.
17381       BaseShAmt = BV->getSplatValue();
17382       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17383         BaseShAmt = SDValue();
17384     } else {
17385       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17386         Amt = Amt.getOperand(0);
17387
17388       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17389       if (SVN && SVN->isSplat()) {
17390         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17391         SDValue InVec = Amt.getOperand(0);
17392         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17393           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17394                  "Unexpected shuffle index found!");
17395           BaseShAmt = InVec.getOperand(SplatIdx);
17396         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17397            if (ConstantSDNode *C =
17398                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17399              if (C->getZExtValue() == SplatIdx)
17400                BaseShAmt = InVec.getOperand(1);
17401            }
17402         }
17403
17404         if (!BaseShAmt)
17405           // Avoid introducing an extract element from a shuffle.
17406           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17407                                   DAG.getIntPtrConstant(SplatIdx, dl));
17408       }
17409     }
17410
17411     if (BaseShAmt.getNode()) {
17412       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17413       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17414         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17415       else if (EltVT.bitsLT(MVT::i32))
17416         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17417
17418       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17419     }
17420   }
17421
17422   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17423   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17424       Amt.getOpcode() == ISD::BITCAST &&
17425       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17426     Amt = Amt.getOperand(0);
17427     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17428                      VT.getVectorNumElements();
17429     std::vector<SDValue> Vals(Ratio);
17430     for (unsigned i = 0; i != Ratio; ++i)
17431       Vals[i] = Amt.getOperand(i);
17432     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17433       for (unsigned j = 0; j != Ratio; ++j)
17434         if (Vals[j] != Amt.getOperand(i + j))
17435           return SDValue();
17436     }
17437
17438     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17439       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17440   }
17441   return SDValue();
17442 }
17443
17444 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17445                           SelectionDAG &DAG) {
17446   MVT VT = Op.getSimpleValueType();
17447   SDLoc dl(Op);
17448   SDValue R = Op.getOperand(0);
17449   SDValue Amt = Op.getOperand(1);
17450
17451   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17452   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17453
17454   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17455     return V;
17456
17457   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17458       return V;
17459
17460   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17461     return Op;
17462
17463   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17464   // shifts per-lane and then shuffle the partial results back together.
17465   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17466     // Splat the shift amounts so the scalar shifts above will catch it.
17467     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17468     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17469     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17470     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17471     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17472   }
17473
17474   // i64 vector arithmetic shift can be emulated with the transform:
17475   // M = lshr(SIGN_BIT, Amt)
17476   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17477   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17478       Op.getOpcode() == ISD::SRA) {
17479     SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17480     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17481     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17482     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17483     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17484     return R;
17485   }
17486
17487   // If possible, lower this packed shift into a vector multiply instead of
17488   // expanding it into a sequence of scalar shifts.
17489   // Do this only if the vector shift count is a constant build_vector.
17490   if (Op.getOpcode() == ISD::SHL &&
17491       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17492        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17493       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17494     SmallVector<SDValue, 8> Elts;
17495     EVT SVT = VT.getScalarType();
17496     unsigned SVTBits = SVT.getSizeInBits();
17497     const APInt &One = APInt(SVTBits, 1);
17498     unsigned NumElems = VT.getVectorNumElements();
17499
17500     for (unsigned i=0; i !=NumElems; ++i) {
17501       SDValue Op = Amt->getOperand(i);
17502       if (Op->getOpcode() == ISD::UNDEF) {
17503         Elts.push_back(Op);
17504         continue;
17505       }
17506
17507       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17508       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17509       uint64_t ShAmt = C.getZExtValue();
17510       if (ShAmt >= SVTBits) {
17511         Elts.push_back(DAG.getUNDEF(SVT));
17512         continue;
17513       }
17514       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17515     }
17516     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17517     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17518   }
17519
17520   // Lower SHL with variable shift amount.
17521   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17522     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17523
17524     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17525                      DAG.getConstant(0x3f800000U, dl, VT));
17526     Op = DAG.getBitcast(MVT::v4f32, Op);
17527     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17528     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17529   }
17530
17531   // If possible, lower this shift as a sequence of two shifts by
17532   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17533   // Example:
17534   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17535   //
17536   // Could be rewritten as:
17537   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17538   //
17539   // The advantage is that the two shifts from the example would be
17540   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17541   // the vector shift into four scalar shifts plus four pairs of vector
17542   // insert/extract.
17543   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17544       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17545     unsigned TargetOpcode = X86ISD::MOVSS;
17546     bool CanBeSimplified;
17547     // The splat value for the first packed shift (the 'X' from the example).
17548     SDValue Amt1 = Amt->getOperand(0);
17549     // The splat value for the second packed shift (the 'Y' from the example).
17550     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17551                                         Amt->getOperand(2);
17552
17553     // See if it is possible to replace this node with a sequence of
17554     // two shifts followed by a MOVSS/MOVSD
17555     if (VT == MVT::v4i32) {
17556       // Check if it is legal to use a MOVSS.
17557       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17558                         Amt2 == Amt->getOperand(3);
17559       if (!CanBeSimplified) {
17560         // Otherwise, check if we can still simplify this node using a MOVSD.
17561         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17562                           Amt->getOperand(2) == Amt->getOperand(3);
17563         TargetOpcode = X86ISD::MOVSD;
17564         Amt2 = Amt->getOperand(2);
17565       }
17566     } else {
17567       // Do similar checks for the case where the machine value type
17568       // is MVT::v8i16.
17569       CanBeSimplified = Amt1 == Amt->getOperand(1);
17570       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17571         CanBeSimplified = Amt2 == Amt->getOperand(i);
17572
17573       if (!CanBeSimplified) {
17574         TargetOpcode = X86ISD::MOVSD;
17575         CanBeSimplified = true;
17576         Amt2 = Amt->getOperand(4);
17577         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17578           CanBeSimplified = Amt1 == Amt->getOperand(i);
17579         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17580           CanBeSimplified = Amt2 == Amt->getOperand(j);
17581       }
17582     }
17583
17584     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17585         isa<ConstantSDNode>(Amt2)) {
17586       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17587       EVT CastVT = MVT::v4i32;
17588       SDValue Splat1 =
17589         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17590       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17591       SDValue Splat2 =
17592         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17593       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17594       if (TargetOpcode == X86ISD::MOVSD)
17595         CastVT = MVT::v2i64;
17596       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17597       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17598       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17599                                             BitCast1, DAG);
17600       return DAG.getBitcast(VT, Result);
17601     }
17602   }
17603
17604   // v4i32 Non Uniform Shifts.
17605   // If the shift amount is constant we can shift each lane using the SSE2
17606   // immediate shifts, else we need to zero-extend each lane to the lower i64
17607   // and shift using the SSE2 variable shifts.
17608   // The separate results can then be blended together.
17609   if (VT == MVT::v4i32) {
17610     unsigned Opc = Op.getOpcode();
17611     SDValue Amt0, Amt1, Amt2, Amt3;
17612     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17613       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17614       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17615       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17616       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17617     } else {
17618       // ISD::SHL is handled above but we include it here for completeness.
17619       switch (Opc) {
17620       default:
17621         llvm_unreachable("Unknown target vector shift node");
17622       case ISD::SHL:
17623         Opc = X86ISD::VSHL;
17624         break;
17625       case ISD::SRL:
17626         Opc = X86ISD::VSRL;
17627         break;
17628       case ISD::SRA:
17629         Opc = X86ISD::VSRA;
17630         break;
17631       }
17632       // The SSE2 shifts use the lower i64 as the same shift amount for
17633       // all lanes and the upper i64 is ignored. These shuffle masks
17634       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17635       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17636       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17637       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17638       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17639       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17640     }
17641
17642     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17643     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17644     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17645     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17646     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17647     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17648     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17649   }
17650
17651   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17652     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17653     unsigned ShiftOpcode = Op->getOpcode();
17654
17655     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17656       // On SSE41 targets we make use of the fact that VSELECT lowers
17657       // to PBLENDVB which selects bytes based just on the sign bit.
17658       if (Subtarget->hasSSE41()) {
17659         V0 = DAG.getBitcast(VT, V0);
17660         V1 = DAG.getBitcast(VT, V1);
17661         Sel = DAG.getBitcast(VT, Sel);
17662         return DAG.getBitcast(SelVT,
17663                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17664       }
17665       // On pre-SSE41 targets we test for the sign bit by comparing to
17666       // zero - a negative value will set all bits of the lanes to true
17667       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17668       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17669       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17670       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17671     };
17672
17673     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17674     // We can safely do this using i16 shifts as we're only interested in
17675     // the 3 lower bits of each byte.
17676     Amt = DAG.getBitcast(ExtVT, Amt);
17677     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17678     Amt = DAG.getBitcast(VT, Amt);
17679
17680     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17681       // r = VSELECT(r, shift(r, 4), a);
17682       SDValue M =
17683           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17684       R = SignBitSelect(VT, Amt, M, R);
17685
17686       // a += a
17687       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17688
17689       // r = VSELECT(r, shift(r, 2), a);
17690       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17691       R = SignBitSelect(VT, Amt, M, R);
17692
17693       // a += a
17694       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17695
17696       // return VSELECT(r, shift(r, 1), a);
17697       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17698       R = SignBitSelect(VT, Amt, M, R);
17699       return R;
17700     }
17701
17702     if (Op->getOpcode() == ISD::SRA) {
17703       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17704       // so we can correctly sign extend. We don't care what happens to the
17705       // lower byte.
17706       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17707       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17708       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17709       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17710       ALo = DAG.getBitcast(ExtVT, ALo);
17711       AHi = DAG.getBitcast(ExtVT, AHi);
17712       RLo = DAG.getBitcast(ExtVT, RLo);
17713       RHi = DAG.getBitcast(ExtVT, RHi);
17714
17715       // r = VSELECT(r, shift(r, 4), a);
17716       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17717                                 DAG.getConstant(4, dl, ExtVT));
17718       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17719                                 DAG.getConstant(4, dl, ExtVT));
17720       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17721       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17722
17723       // a += a
17724       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17725       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17726
17727       // r = VSELECT(r, shift(r, 2), a);
17728       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17729                         DAG.getConstant(2, dl, ExtVT));
17730       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17731                         DAG.getConstant(2, dl, ExtVT));
17732       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17733       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17734
17735       // a += a
17736       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17737       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17738
17739       // r = VSELECT(r, shift(r, 1), a);
17740       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17741                         DAG.getConstant(1, dl, ExtVT));
17742       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17743                         DAG.getConstant(1, dl, ExtVT));
17744       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17745       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17746
17747       // Logical shift the result back to the lower byte, leaving a zero upper
17748       // byte
17749       // meaning that we can safely pack with PACKUSWB.
17750       RLo =
17751           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17752       RHi =
17753           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17754       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17755     }
17756   }
17757
17758   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17759   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17760   // solution better.
17761   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17762     MVT ExtVT = MVT::v8i32;
17763     unsigned ExtOpc =
17764         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17765     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17766     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17767     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17768                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17769   }
17770
17771   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17772     MVT ExtVT = MVT::v8i32;
17773     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17774     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17775     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17776     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17777     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17778     ALo = DAG.getBitcast(ExtVT, ALo);
17779     AHi = DAG.getBitcast(ExtVT, AHi);
17780     RLo = DAG.getBitcast(ExtVT, RLo);
17781     RHi = DAG.getBitcast(ExtVT, RHi);
17782     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17783     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17784     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17785     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17786     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17787   }
17788
17789   if (VT == MVT::v8i16) {
17790     unsigned ShiftOpcode = Op->getOpcode();
17791
17792     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17793       // On SSE41 targets we make use of the fact that VSELECT lowers
17794       // to PBLENDVB which selects bytes based just on the sign bit.
17795       if (Subtarget->hasSSE41()) {
17796         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17797         V0 = DAG.getBitcast(ExtVT, V0);
17798         V1 = DAG.getBitcast(ExtVT, V1);
17799         Sel = DAG.getBitcast(ExtVT, Sel);
17800         return DAG.getBitcast(
17801             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17802       }
17803       // On pre-SSE41 targets we splat the sign bit - a negative value will
17804       // set all bits of the lanes to true and VSELECT uses that in
17805       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17806       SDValue C =
17807           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17808       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17809     };
17810
17811     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17812     if (Subtarget->hasSSE41()) {
17813       // On SSE41 targets we need to replicate the shift mask in both
17814       // bytes for PBLENDVB.
17815       Amt = DAG.getNode(
17816           ISD::OR, dl, VT,
17817           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17818           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17819     } else {
17820       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17821     }
17822
17823     // r = VSELECT(r, shift(r, 8), a);
17824     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17825     R = SignBitSelect(Amt, M, R);
17826
17827     // a += a
17828     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17829
17830     // r = VSELECT(r, shift(r, 4), a);
17831     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17832     R = SignBitSelect(Amt, M, R);
17833
17834     // a += a
17835     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17836
17837     // r = VSELECT(r, shift(r, 2), a);
17838     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17839     R = SignBitSelect(Amt, M, R);
17840
17841     // a += a
17842     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17843
17844     // return VSELECT(r, shift(r, 1), a);
17845     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17846     R = SignBitSelect(Amt, M, R);
17847     return R;
17848   }
17849
17850   // Decompose 256-bit shifts into smaller 128-bit shifts.
17851   if (VT.is256BitVector()) {
17852     unsigned NumElems = VT.getVectorNumElements();
17853     MVT EltVT = VT.getVectorElementType();
17854     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17855
17856     // Extract the two vectors
17857     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17858     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17859
17860     // Recreate the shift amount vectors
17861     SDValue Amt1, Amt2;
17862     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17863       // Constant shift amount
17864       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17865       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17866       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17867
17868       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17869       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17870     } else {
17871       // Variable shift amount
17872       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17873       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17874     }
17875
17876     // Issue new vector shifts for the smaller types
17877     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17878     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17879
17880     // Concatenate the result back
17881     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17882   }
17883
17884   return SDValue();
17885 }
17886
17887 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17888   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17889   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17890   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17891   // has only one use.
17892   SDNode *N = Op.getNode();
17893   SDValue LHS = N->getOperand(0);
17894   SDValue RHS = N->getOperand(1);
17895   unsigned BaseOp = 0;
17896   unsigned Cond = 0;
17897   SDLoc DL(Op);
17898   switch (Op.getOpcode()) {
17899   default: llvm_unreachable("Unknown ovf instruction!");
17900   case ISD::SADDO:
17901     // A subtract of one will be selected as a INC. Note that INC doesn't
17902     // set CF, so we can't do this for UADDO.
17903     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17904       if (C->isOne()) {
17905         BaseOp = X86ISD::INC;
17906         Cond = X86::COND_O;
17907         break;
17908       }
17909     BaseOp = X86ISD::ADD;
17910     Cond = X86::COND_O;
17911     break;
17912   case ISD::UADDO:
17913     BaseOp = X86ISD::ADD;
17914     Cond = X86::COND_B;
17915     break;
17916   case ISD::SSUBO:
17917     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17918     // set CF, so we can't do this for USUBO.
17919     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17920       if (C->isOne()) {
17921         BaseOp = X86ISD::DEC;
17922         Cond = X86::COND_O;
17923         break;
17924       }
17925     BaseOp = X86ISD::SUB;
17926     Cond = X86::COND_O;
17927     break;
17928   case ISD::USUBO:
17929     BaseOp = X86ISD::SUB;
17930     Cond = X86::COND_B;
17931     break;
17932   case ISD::SMULO:
17933     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17934     Cond = X86::COND_O;
17935     break;
17936   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17937     if (N->getValueType(0) == MVT::i8) {
17938       BaseOp = X86ISD::UMUL8;
17939       Cond = X86::COND_O;
17940       break;
17941     }
17942     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17943                                  MVT::i32);
17944     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17945
17946     SDValue SetCC =
17947       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17948                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17949                   SDValue(Sum.getNode(), 2));
17950
17951     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17952   }
17953   }
17954
17955   // Also sets EFLAGS.
17956   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17957   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17958
17959   SDValue SetCC =
17960     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17961                 DAG.getConstant(Cond, DL, MVT::i32),
17962                 SDValue(Sum.getNode(), 1));
17963
17964   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17965 }
17966
17967 /// Returns true if the operand type is exactly twice the native width, and
17968 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17969 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17970 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17971 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
17972   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17973
17974   if (OpWidth == 64)
17975     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17976   else if (OpWidth == 128)
17977     return Subtarget->hasCmpxchg16b();
17978   else
17979     return false;
17980 }
17981
17982 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17983   return needsCmpXchgNb(SI->getValueOperand()->getType());
17984 }
17985
17986 // Note: this turns large loads into lock cmpxchg8b/16b.
17987 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17988 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17989   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17990   return needsCmpXchgNb(PTy->getElementType());
17991 }
17992
17993 TargetLoweringBase::AtomicRMWExpansionKind
17994 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17995   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17996   Type *MemType = AI->getType();
17997
17998   // If the operand is too big, we must see if cmpxchg8/16b is available
17999   // and default to library calls otherwise.
18000   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18001     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18002                                    : AtomicRMWExpansionKind::None;
18003   }
18004
18005   AtomicRMWInst::BinOp Op = AI->getOperation();
18006   switch (Op) {
18007   default:
18008     llvm_unreachable("Unknown atomic operation");
18009   case AtomicRMWInst::Xchg:
18010   case AtomicRMWInst::Add:
18011   case AtomicRMWInst::Sub:
18012     // It's better to use xadd, xsub or xchg for these in all cases.
18013     return AtomicRMWExpansionKind::None;
18014   case AtomicRMWInst::Or:
18015   case AtomicRMWInst::And:
18016   case AtomicRMWInst::Xor:
18017     // If the atomicrmw's result isn't actually used, we can just add a "lock"
18018     // prefix to a normal instruction for these operations.
18019     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18020                             : AtomicRMWExpansionKind::None;
18021   case AtomicRMWInst::Nand:
18022   case AtomicRMWInst::Max:
18023   case AtomicRMWInst::Min:
18024   case AtomicRMWInst::UMax:
18025   case AtomicRMWInst::UMin:
18026     // These always require a non-trivial set of data operations on x86. We must
18027     // use a cmpxchg loop.
18028     return AtomicRMWExpansionKind::CmpXChg;
18029   }
18030 }
18031
18032 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18033   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18034   // no-sse2). There isn't any reason to disable it if the target processor
18035   // supports it.
18036   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18037 }
18038
18039 LoadInst *
18040 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18041   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18042   Type *MemType = AI->getType();
18043   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18044   // there is no benefit in turning such RMWs into loads, and it is actually
18045   // harmful as it introduces a mfence.
18046   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18047     return nullptr;
18048
18049   auto Builder = IRBuilder<>(AI);
18050   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18051   auto SynchScope = AI->getSynchScope();
18052   // We must restrict the ordering to avoid generating loads with Release or
18053   // ReleaseAcquire orderings.
18054   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18055   auto Ptr = AI->getPointerOperand();
18056
18057   // Before the load we need a fence. Here is an example lifted from
18058   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18059   // is required:
18060   // Thread 0:
18061   //   x.store(1, relaxed);
18062   //   r1 = y.fetch_add(0, release);
18063   // Thread 1:
18064   //   y.fetch_add(42, acquire);
18065   //   r2 = x.load(relaxed);
18066   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18067   // lowered to just a load without a fence. A mfence flushes the store buffer,
18068   // making the optimization clearly correct.
18069   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18070   // otherwise, we might be able to be more aggressive on relaxed idempotent
18071   // rmw. In practice, they do not look useful, so we don't try to be
18072   // especially clever.
18073   if (SynchScope == SingleThread)
18074     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18075     // the IR level, so we must wrap it in an intrinsic.
18076     return nullptr;
18077
18078   if (!hasMFENCE(*Subtarget))
18079     // FIXME: it might make sense to use a locked operation here but on a
18080     // different cache-line to prevent cache-line bouncing. In practice it
18081     // is probably a small win, and x86 processors without mfence are rare
18082     // enough that we do not bother.
18083     return nullptr;
18084
18085   Function *MFence =
18086       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18087   Builder.CreateCall(MFence, {});
18088
18089   // Finally we can emit the atomic load.
18090   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18091           AI->getType()->getPrimitiveSizeInBits());
18092   Loaded->setAtomic(Order, SynchScope);
18093   AI->replaceAllUsesWith(Loaded);
18094   AI->eraseFromParent();
18095   return Loaded;
18096 }
18097
18098 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18099                                  SelectionDAG &DAG) {
18100   SDLoc dl(Op);
18101   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18102     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18103   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18104     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18105
18106   // The only fence that needs an instruction is a sequentially-consistent
18107   // cross-thread fence.
18108   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18109     if (hasMFENCE(*Subtarget))
18110       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18111
18112     SDValue Chain = Op.getOperand(0);
18113     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18114     SDValue Ops[] = {
18115       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18116       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18117       DAG.getRegister(0, MVT::i32),            // Index
18118       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18119       DAG.getRegister(0, MVT::i32),            // Segment.
18120       Zero,
18121       Chain
18122     };
18123     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18124     return SDValue(Res, 0);
18125   }
18126
18127   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18128   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18129 }
18130
18131 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18132                              SelectionDAG &DAG) {
18133   MVT T = Op.getSimpleValueType();
18134   SDLoc DL(Op);
18135   unsigned Reg = 0;
18136   unsigned size = 0;
18137   switch(T.SimpleTy) {
18138   default: llvm_unreachable("Invalid value type!");
18139   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18140   case MVT::i16: Reg = X86::AX;  size = 2; break;
18141   case MVT::i32: Reg = X86::EAX; size = 4; break;
18142   case MVT::i64:
18143     assert(Subtarget->is64Bit() && "Node not type legal!");
18144     Reg = X86::RAX; size = 8;
18145     break;
18146   }
18147   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18148                                   Op.getOperand(2), SDValue());
18149   SDValue Ops[] = { cpIn.getValue(0),
18150                     Op.getOperand(1),
18151                     Op.getOperand(3),
18152                     DAG.getTargetConstant(size, DL, MVT::i8),
18153                     cpIn.getValue(1) };
18154   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18155   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18156   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18157                                            Ops, T, MMO);
18158
18159   SDValue cpOut =
18160     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18161   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18162                                       MVT::i32, cpOut.getValue(2));
18163   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18164                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18165                                 EFLAGS);
18166
18167   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18168   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18169   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18170   return SDValue();
18171 }
18172
18173 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18174                             SelectionDAG &DAG) {
18175   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18176   MVT DstVT = Op.getSimpleValueType();
18177
18178   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18179     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18180     if (DstVT != MVT::f64)
18181       // This conversion needs to be expanded.
18182       return SDValue();
18183
18184     SDValue InVec = Op->getOperand(0);
18185     SDLoc dl(Op);
18186     unsigned NumElts = SrcVT.getVectorNumElements();
18187     EVT SVT = SrcVT.getVectorElementType();
18188
18189     // Widen the vector in input in the case of MVT::v2i32.
18190     // Example: from MVT::v2i32 to MVT::v4i32.
18191     SmallVector<SDValue, 16> Elts;
18192     for (unsigned i = 0, e = NumElts; i != e; ++i)
18193       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18194                                  DAG.getIntPtrConstant(i, dl)));
18195
18196     // Explicitly mark the extra elements as Undef.
18197     Elts.append(NumElts, DAG.getUNDEF(SVT));
18198
18199     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18200     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18201     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18202     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18203                        DAG.getIntPtrConstant(0, dl));
18204   }
18205
18206   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18207          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18208   assert((DstVT == MVT::i64 ||
18209           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18210          "Unexpected custom BITCAST");
18211   // i64 <=> MMX conversions are Legal.
18212   if (SrcVT==MVT::i64 && DstVT.isVector())
18213     return Op;
18214   if (DstVT==MVT::i64 && SrcVT.isVector())
18215     return Op;
18216   // MMX <=> MMX conversions are Legal.
18217   if (SrcVT.isVector() && DstVT.isVector())
18218     return Op;
18219   // All other conversions need to be expanded.
18220   return SDValue();
18221 }
18222
18223 /// Compute the horizontal sum of bytes in V for the elements of VT.
18224 ///
18225 /// Requires V to be a byte vector and VT to be an integer vector type with
18226 /// wider elements than V's type. The width of the elements of VT determines
18227 /// how many bytes of V are summed horizontally to produce each element of the
18228 /// result.
18229 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18230                                       const X86Subtarget *Subtarget,
18231                                       SelectionDAG &DAG) {
18232   SDLoc DL(V);
18233   MVT ByteVecVT = V.getSimpleValueType();
18234   MVT EltVT = VT.getVectorElementType();
18235   int NumElts = VT.getVectorNumElements();
18236   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18237          "Expected value to have byte element type.");
18238   assert(EltVT != MVT::i8 &&
18239          "Horizontal byte sum only makes sense for wider elements!");
18240   unsigned VecSize = VT.getSizeInBits();
18241   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18242
18243   // PSADBW instruction horizontally add all bytes and leave the result in i64
18244   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18245   if (EltVT == MVT::i64) {
18246     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18247     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18248     return DAG.getBitcast(VT, V);
18249   }
18250
18251   if (EltVT == MVT::i32) {
18252     // We unpack the low half and high half into i32s interleaved with zeros so
18253     // that we can use PSADBW to horizontally sum them. The most useful part of
18254     // this is that it lines up the results of two PSADBW instructions to be
18255     // two v2i64 vectors which concatenated are the 4 population counts. We can
18256     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18257     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18258     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18259     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18260
18261     // Do the horizontal sums into two v2i64s.
18262     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18263     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18264                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18265     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18266                        DAG.getBitcast(ByteVecVT, High), Zeros);
18267
18268     // Merge them together.
18269     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18270     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18271                     DAG.getBitcast(ShortVecVT, Low),
18272                     DAG.getBitcast(ShortVecVT, High));
18273
18274     return DAG.getBitcast(VT, V);
18275   }
18276
18277   // The only element type left is i16.
18278   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18279
18280   // To obtain pop count for each i16 element starting from the pop count for
18281   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18282   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18283   // directly supported.
18284   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18285   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18286   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18287   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18288                   DAG.getBitcast(ByteVecVT, V));
18289   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18290 }
18291
18292 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18293                                         const X86Subtarget *Subtarget,
18294                                         SelectionDAG &DAG) {
18295   MVT VT = Op.getSimpleValueType();
18296   MVT EltVT = VT.getVectorElementType();
18297   unsigned VecSize = VT.getSizeInBits();
18298
18299   // Implement a lookup table in register by using an algorithm based on:
18300   // http://wm.ite.pl/articles/sse-popcount.html
18301   //
18302   // The general idea is that every lower byte nibble in the input vector is an
18303   // index into a in-register pre-computed pop count table. We then split up the
18304   // input vector in two new ones: (1) a vector with only the shifted-right
18305   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18306   // masked out higher ones) for each byte. PSHUB is used separately with both
18307   // to index the in-register table. Next, both are added and the result is a
18308   // i8 vector where each element contains the pop count for input byte.
18309   //
18310   // To obtain the pop count for elements != i8, we follow up with the same
18311   // approach and use additional tricks as described below.
18312   //
18313   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18314                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18315                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18316                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18317
18318   int NumByteElts = VecSize / 8;
18319   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18320   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18321   SmallVector<SDValue, 16> LUTVec;
18322   for (int i = 0; i < NumByteElts; ++i)
18323     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18324   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18325   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18326                                   DAG.getConstant(0x0F, DL, MVT::i8));
18327   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18328
18329   // High nibbles
18330   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18331   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18332   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18333
18334   // Low nibbles
18335   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18336
18337   // The input vector is used as the shuffle mask that index elements into the
18338   // LUT. After counting low and high nibbles, add the vector to obtain the
18339   // final pop count per i8 element.
18340   SDValue HighPopCnt =
18341       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18342   SDValue LowPopCnt =
18343       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18344   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18345
18346   if (EltVT == MVT::i8)
18347     return PopCnt;
18348
18349   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18350 }
18351
18352 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18353                                        const X86Subtarget *Subtarget,
18354                                        SelectionDAG &DAG) {
18355   MVT VT = Op.getSimpleValueType();
18356   assert(VT.is128BitVector() &&
18357          "Only 128-bit vector bitmath lowering supported.");
18358
18359   int VecSize = VT.getSizeInBits();
18360   MVT EltVT = VT.getVectorElementType();
18361   int Len = EltVT.getSizeInBits();
18362
18363   // This is the vectorized version of the "best" algorithm from
18364   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18365   // with a minor tweak to use a series of adds + shifts instead of vector
18366   // multiplications. Implemented for all integer vector types. We only use
18367   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18368   // much faster, even faster than using native popcnt instructions.
18369
18370   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18371     MVT VT = V.getSimpleValueType();
18372     SmallVector<SDValue, 32> Shifters(
18373         VT.getVectorNumElements(),
18374         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18375     return DAG.getNode(OpCode, DL, VT, V,
18376                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18377   };
18378   auto GetMask = [&](SDValue V, APInt Mask) {
18379     MVT VT = V.getSimpleValueType();
18380     SmallVector<SDValue, 32> Masks(
18381         VT.getVectorNumElements(),
18382         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18383     return DAG.getNode(ISD::AND, DL, VT, V,
18384                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18385   };
18386
18387   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18388   // x86, so set the SRL type to have elements at least i16 wide. This is
18389   // correct because all of our SRLs are followed immediately by a mask anyways
18390   // that handles any bits that sneak into the high bits of the byte elements.
18391   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18392
18393   SDValue V = Op;
18394
18395   // v = v - ((v >> 1) & 0x55555555...)
18396   SDValue Srl =
18397       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18398   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18399   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18400
18401   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18402   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18403   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18404   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18405   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18406
18407   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18408   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18409   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18410   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18411
18412   // At this point, V contains the byte-wise population count, and we are
18413   // merely doing a horizontal sum if necessary to get the wider element
18414   // counts.
18415   if (EltVT == MVT::i8)
18416     return V;
18417
18418   return LowerHorizontalByteSum(
18419       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18420       DAG);
18421 }
18422
18423 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18424                                 SelectionDAG &DAG) {
18425   MVT VT = Op.getSimpleValueType();
18426   // FIXME: Need to add AVX-512 support here!
18427   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18428          "Unknown CTPOP type to handle");
18429   SDLoc DL(Op.getNode());
18430   SDValue Op0 = Op.getOperand(0);
18431
18432   if (!Subtarget->hasSSSE3()) {
18433     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18434     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18435     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18436   }
18437
18438   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18439     unsigned NumElems = VT.getVectorNumElements();
18440
18441     // Extract each 128-bit vector, compute pop count and concat the result.
18442     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18443     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18444
18445     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18446                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18447                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18448   }
18449
18450   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18451 }
18452
18453 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18454                           SelectionDAG &DAG) {
18455   assert(Op.getValueType().isVector() &&
18456          "We only do custom lowering for vector population count.");
18457   return LowerVectorCTPOP(Op, Subtarget, DAG);
18458 }
18459
18460 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18461   SDNode *Node = Op.getNode();
18462   SDLoc dl(Node);
18463   EVT T = Node->getValueType(0);
18464   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18465                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18466   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18467                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18468                        Node->getOperand(0),
18469                        Node->getOperand(1), negOp,
18470                        cast<AtomicSDNode>(Node)->getMemOperand(),
18471                        cast<AtomicSDNode>(Node)->getOrdering(),
18472                        cast<AtomicSDNode>(Node)->getSynchScope());
18473 }
18474
18475 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18476   SDNode *Node = Op.getNode();
18477   SDLoc dl(Node);
18478   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18479
18480   // Convert seq_cst store -> xchg
18481   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18482   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18483   //        (The only way to get a 16-byte store is cmpxchg16b)
18484   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18485   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18486       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18487     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18488                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18489                                  Node->getOperand(0),
18490                                  Node->getOperand(1), Node->getOperand(2),
18491                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18492                                  cast<AtomicSDNode>(Node)->getOrdering(),
18493                                  cast<AtomicSDNode>(Node)->getSynchScope());
18494     return Swap.getValue(1);
18495   }
18496   // Other atomic stores have a simple pattern.
18497   return Op;
18498 }
18499
18500 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18501   EVT VT = Op.getNode()->getSimpleValueType(0);
18502
18503   // Let legalize expand this if it isn't a legal type yet.
18504   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18505     return SDValue();
18506
18507   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18508
18509   unsigned Opc;
18510   bool ExtraOp = false;
18511   switch (Op.getOpcode()) {
18512   default: llvm_unreachable("Invalid code");
18513   case ISD::ADDC: Opc = X86ISD::ADD; break;
18514   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18515   case ISD::SUBC: Opc = X86ISD::SUB; break;
18516   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18517   }
18518
18519   if (!ExtraOp)
18520     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18521                        Op.getOperand(1));
18522   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18523                      Op.getOperand(1), Op.getOperand(2));
18524 }
18525
18526 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18527                             SelectionDAG &DAG) {
18528   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18529
18530   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18531   // which returns the values as { float, float } (in XMM0) or
18532   // { double, double } (which is returned in XMM0, XMM1).
18533   SDLoc dl(Op);
18534   SDValue Arg = Op.getOperand(0);
18535   EVT ArgVT = Arg.getValueType();
18536   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18537
18538   TargetLowering::ArgListTy Args;
18539   TargetLowering::ArgListEntry Entry;
18540
18541   Entry.Node = Arg;
18542   Entry.Ty = ArgTy;
18543   Entry.isSExt = false;
18544   Entry.isZExt = false;
18545   Args.push_back(Entry);
18546
18547   bool isF64 = ArgVT == MVT::f64;
18548   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18549   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18550   // the results are returned via SRet in memory.
18551   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18553   SDValue Callee =
18554       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18555
18556   Type *RetTy = isF64
18557     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18558     : (Type*)VectorType::get(ArgTy, 4);
18559
18560   TargetLowering::CallLoweringInfo CLI(DAG);
18561   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18562     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18563
18564   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18565
18566   if (isF64)
18567     // Returned in xmm0 and xmm1.
18568     return CallResult.first;
18569
18570   // Returned in bits 0:31 and 32:64 xmm0.
18571   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18572                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18573   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18574                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18575   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18576   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18577 }
18578
18579 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18580                              SelectionDAG &DAG) {
18581   assert(Subtarget->hasAVX512() &&
18582          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18583
18584   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18585   EVT VT = N->getValue().getValueType();
18586   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18587   SDLoc dl(Op);
18588
18589   // X86 scatter kills mask register, so its type should be added to
18590   // the list of return values
18591   if (N->getNumValues() == 1) {
18592     SDValue Index = N->getIndex();
18593     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18594         !Index.getValueType().is512BitVector())
18595       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18596
18597     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18598     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18599                       N->getOperand(3), Index };
18600
18601     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18602     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18603     return SDValue(NewScatter.getNode(), 0);
18604   }
18605   return Op;
18606 }
18607
18608 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18609                             SelectionDAG &DAG) {
18610   assert(Subtarget->hasAVX512() &&
18611          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18612
18613   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18614   EVT VT = Op.getValueType();
18615   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18616   SDLoc dl(Op);
18617
18618   SDValue Index = N->getIndex();
18619   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18620       !Index.getValueType().is512BitVector()) {
18621     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18622     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18623                       N->getOperand(3), Index };
18624     DAG.UpdateNodeOperands(N, Ops);
18625   }
18626   return Op;
18627 }
18628
18629 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18630                                                     SelectionDAG &DAG) const {
18631   // TODO: Eventually, the lowering of these nodes should be informed by or
18632   // deferred to the GC strategy for the function in which they appear. For
18633   // now, however, they must be lowered to something. Since they are logically
18634   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18635   // require special handling for these nodes), lower them as literal NOOPs for
18636   // the time being.
18637   SmallVector<SDValue, 2> Ops;
18638
18639   Ops.push_back(Op.getOperand(0));
18640   if (Op->getGluedNode())
18641     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18642
18643   SDLoc OpDL(Op);
18644   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18645   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18646
18647   return NOOP;
18648 }
18649
18650 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18651                                                   SelectionDAG &DAG) const {
18652   // TODO: Eventually, the lowering of these nodes should be informed by or
18653   // deferred to the GC strategy for the function in which they appear. For
18654   // now, however, they must be lowered to something. Since they are logically
18655   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18656   // require special handling for these nodes), lower them as literal NOOPs for
18657   // the time being.
18658   SmallVector<SDValue, 2> Ops;
18659
18660   Ops.push_back(Op.getOperand(0));
18661   if (Op->getGluedNode())
18662     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18663
18664   SDLoc OpDL(Op);
18665   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18666   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18667
18668   return NOOP;
18669 }
18670
18671 /// LowerOperation - Provide custom lowering hooks for some operations.
18672 ///
18673 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18674   switch (Op.getOpcode()) {
18675   default: llvm_unreachable("Should not custom lower this!");
18676   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18677   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18678     return LowerCMP_SWAP(Op, Subtarget, DAG);
18679   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18680   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18681   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18682   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18683   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18684   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18685   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18686   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18687   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18688   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18689   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18690   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18691   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18692   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18693   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18694   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18695   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18696   case ISD::SHL_PARTS:
18697   case ISD::SRA_PARTS:
18698   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18699   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18700   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18701   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18702   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18703   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18704   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18705   case ISD::SIGN_EXTEND_VECTOR_INREG:
18706     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18707   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18708   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18709   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18710   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18711   case ISD::FABS:
18712   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18713   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18714   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18715   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18716   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18717   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18718   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18719   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18720   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18721   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18722   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18723   case ISD::INTRINSIC_VOID:
18724   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18725   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18726   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18727   case ISD::FRAME_TO_ARGS_OFFSET:
18728                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18729   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18730   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18731   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18732   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18733   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18734   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18735   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18736   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18737   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18738   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18739   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18740   case ISD::UMUL_LOHI:
18741   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18742   case ISD::SRA:
18743   case ISD::SRL:
18744   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18745   case ISD::SADDO:
18746   case ISD::UADDO:
18747   case ISD::SSUBO:
18748   case ISD::USUBO:
18749   case ISD::SMULO:
18750   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18751   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18752   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18753   case ISD::ADDC:
18754   case ISD::ADDE:
18755   case ISD::SUBC:
18756   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18757   case ISD::ADD:                return LowerADD(Op, DAG);
18758   case ISD::SUB:                return LowerSUB(Op, DAG);
18759   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18760   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18761   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18762   case ISD::GC_TRANSITION_START:
18763                                 return LowerGC_TRANSITION_START(Op, DAG);
18764   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18765   }
18766 }
18767
18768 /// ReplaceNodeResults - Replace a node with an illegal result type
18769 /// with a new node built out of custom code.
18770 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18771                                            SmallVectorImpl<SDValue>&Results,
18772                                            SelectionDAG &DAG) const {
18773   SDLoc dl(N);
18774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18775   switch (N->getOpcode()) {
18776   default:
18777     llvm_unreachable("Do not know how to custom type legalize this operation!");
18778   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18779   case X86ISD::FMINC:
18780   case X86ISD::FMIN:
18781   case X86ISD::FMAXC:
18782   case X86ISD::FMAX: {
18783     EVT VT = N->getValueType(0);
18784     if (VT != MVT::v2f32)
18785       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18786     SDValue UNDEF = DAG.getUNDEF(VT);
18787     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18788                               N->getOperand(0), UNDEF);
18789     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18790                               N->getOperand(1), UNDEF);
18791     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18792     return;
18793   }
18794   case ISD::SIGN_EXTEND_INREG:
18795   case ISD::ADDC:
18796   case ISD::ADDE:
18797   case ISD::SUBC:
18798   case ISD::SUBE:
18799     // We don't want to expand or promote these.
18800     return;
18801   case ISD::SDIV:
18802   case ISD::UDIV:
18803   case ISD::SREM:
18804   case ISD::UREM:
18805   case ISD::SDIVREM:
18806   case ISD::UDIVREM: {
18807     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18808     Results.push_back(V);
18809     return;
18810   }
18811   case ISD::FP_TO_SINT:
18812     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18813     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18814     if (N->getOperand(0).getValueType() == MVT::f16)
18815       break;
18816     // fallthrough
18817   case ISD::FP_TO_UINT: {
18818     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18819
18820     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18821       return;
18822
18823     std::pair<SDValue,SDValue> Vals =
18824         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18825     SDValue FIST = Vals.first, StackSlot = Vals.second;
18826     if (FIST.getNode()) {
18827       EVT VT = N->getValueType(0);
18828       // Return a load from the stack slot.
18829       if (StackSlot.getNode())
18830         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18831                                       MachinePointerInfo(),
18832                                       false, false, false, 0));
18833       else
18834         Results.push_back(FIST);
18835     }
18836     return;
18837   }
18838   case ISD::UINT_TO_FP: {
18839     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18840     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18841         N->getValueType(0) != MVT::v2f32)
18842       return;
18843     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18844                                  N->getOperand(0));
18845     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18846                                      MVT::f64);
18847     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18848     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18849                              DAG.getBitcast(MVT::v2i64, VBias));
18850     Or = DAG.getBitcast(MVT::v2f64, Or);
18851     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18852     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18853     return;
18854   }
18855   case ISD::FP_ROUND: {
18856     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18857         return;
18858     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18859     Results.push_back(V);
18860     return;
18861   }
18862   case ISD::FP_EXTEND: {
18863     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18864     // No other ValueType for FP_EXTEND should reach this point.
18865     assert(N->getValueType(0) == MVT::v2f32 &&
18866            "Do not know how to legalize this Node");
18867     return;
18868   }
18869   case ISD::INTRINSIC_W_CHAIN: {
18870     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18871     switch (IntNo) {
18872     default : llvm_unreachable("Do not know how to custom type "
18873                                "legalize this intrinsic operation!");
18874     case Intrinsic::x86_rdtsc:
18875       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18876                                      Results);
18877     case Intrinsic::x86_rdtscp:
18878       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18879                                      Results);
18880     case Intrinsic::x86_rdpmc:
18881       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18882     }
18883   }
18884   case ISD::READCYCLECOUNTER: {
18885     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18886                                    Results);
18887   }
18888   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18889     EVT T = N->getValueType(0);
18890     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18891     bool Regs64bit = T == MVT::i128;
18892     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18893     SDValue cpInL, cpInH;
18894     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18895                         DAG.getConstant(0, dl, HalfT));
18896     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18897                         DAG.getConstant(1, dl, HalfT));
18898     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18899                              Regs64bit ? X86::RAX : X86::EAX,
18900                              cpInL, SDValue());
18901     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18902                              Regs64bit ? X86::RDX : X86::EDX,
18903                              cpInH, cpInL.getValue(1));
18904     SDValue swapInL, swapInH;
18905     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18906                           DAG.getConstant(0, dl, HalfT));
18907     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18908                           DAG.getConstant(1, dl, HalfT));
18909     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18910                                Regs64bit ? X86::RBX : X86::EBX,
18911                                swapInL, cpInH.getValue(1));
18912     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18913                                Regs64bit ? X86::RCX : X86::ECX,
18914                                swapInH, swapInL.getValue(1));
18915     SDValue Ops[] = { swapInH.getValue(0),
18916                       N->getOperand(1),
18917                       swapInH.getValue(1) };
18918     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18919     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18920     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18921                                   X86ISD::LCMPXCHG8_DAG;
18922     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18923     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18924                                         Regs64bit ? X86::RAX : X86::EAX,
18925                                         HalfT, Result.getValue(1));
18926     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18927                                         Regs64bit ? X86::RDX : X86::EDX,
18928                                         HalfT, cpOutL.getValue(2));
18929     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18930
18931     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18932                                         MVT::i32, cpOutH.getValue(2));
18933     SDValue Success =
18934         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18935                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18936     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18937
18938     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18939     Results.push_back(Success);
18940     Results.push_back(EFLAGS.getValue(1));
18941     return;
18942   }
18943   case ISD::ATOMIC_SWAP:
18944   case ISD::ATOMIC_LOAD_ADD:
18945   case ISD::ATOMIC_LOAD_SUB:
18946   case ISD::ATOMIC_LOAD_AND:
18947   case ISD::ATOMIC_LOAD_OR:
18948   case ISD::ATOMIC_LOAD_XOR:
18949   case ISD::ATOMIC_LOAD_NAND:
18950   case ISD::ATOMIC_LOAD_MIN:
18951   case ISD::ATOMIC_LOAD_MAX:
18952   case ISD::ATOMIC_LOAD_UMIN:
18953   case ISD::ATOMIC_LOAD_UMAX:
18954   case ISD::ATOMIC_LOAD: {
18955     // Delegate to generic TypeLegalization. Situations we can really handle
18956     // should have already been dealt with by AtomicExpandPass.cpp.
18957     break;
18958   }
18959   case ISD::BITCAST: {
18960     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18961     EVT DstVT = N->getValueType(0);
18962     EVT SrcVT = N->getOperand(0)->getValueType(0);
18963
18964     if (SrcVT != MVT::f64 ||
18965         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18966       return;
18967
18968     unsigned NumElts = DstVT.getVectorNumElements();
18969     EVT SVT = DstVT.getVectorElementType();
18970     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18971     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18972                                    MVT::v2f64, N->getOperand(0));
18973     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18974
18975     if (ExperimentalVectorWideningLegalization) {
18976       // If we are legalizing vectors by widening, we already have the desired
18977       // legal vector type, just return it.
18978       Results.push_back(ToVecInt);
18979       return;
18980     }
18981
18982     SmallVector<SDValue, 8> Elts;
18983     for (unsigned i = 0, e = NumElts; i != e; ++i)
18984       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18985                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18986
18987     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18988   }
18989   }
18990 }
18991
18992 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18993   switch ((X86ISD::NodeType)Opcode) {
18994   case X86ISD::FIRST_NUMBER:       break;
18995   case X86ISD::BSF:                return "X86ISD::BSF";
18996   case X86ISD::BSR:                return "X86ISD::BSR";
18997   case X86ISD::SHLD:               return "X86ISD::SHLD";
18998   case X86ISD::SHRD:               return "X86ISD::SHRD";
18999   case X86ISD::FAND:               return "X86ISD::FAND";
19000   case X86ISD::FANDN:              return "X86ISD::FANDN";
19001   case X86ISD::FOR:                return "X86ISD::FOR";
19002   case X86ISD::FXOR:               return "X86ISD::FXOR";
19003   case X86ISD::FILD:               return "X86ISD::FILD";
19004   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
19005   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19006   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19007   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19008   case X86ISD::FLD:                return "X86ISD::FLD";
19009   case X86ISD::FST:                return "X86ISD::FST";
19010   case X86ISD::CALL:               return "X86ISD::CALL";
19011   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
19012   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
19013   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
19014   case X86ISD::BT:                 return "X86ISD::BT";
19015   case X86ISD::CMP:                return "X86ISD::CMP";
19016   case X86ISD::COMI:               return "X86ISD::COMI";
19017   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
19018   case X86ISD::CMPM:               return "X86ISD::CMPM";
19019   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
19020   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
19021   case X86ISD::SETCC:              return "X86ISD::SETCC";
19022   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
19023   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
19024   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
19025   case X86ISD::CMOV:               return "X86ISD::CMOV";
19026   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
19027   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
19028   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
19029   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
19030   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
19031   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19032   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19033   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19034   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19035   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19036   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19037   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19038   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19039   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19040   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19041   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19042   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19043   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19044   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19045   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19046   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19047   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19048   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19049   case X86ISD::HADD:               return "X86ISD::HADD";
19050   case X86ISD::HSUB:               return "X86ISD::HSUB";
19051   case X86ISD::FHADD:              return "X86ISD::FHADD";
19052   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19053   case X86ISD::ABS:                return "X86ISD::ABS";
19054   case X86ISD::FMAX:               return "X86ISD::FMAX";
19055   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19056   case X86ISD::FMIN:               return "X86ISD::FMIN";
19057   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19058   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19059   case X86ISD::FMINC:              return "X86ISD::FMINC";
19060   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19061   case X86ISD::FRCP:               return "X86ISD::FRCP";
19062   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19063   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19064   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19065   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19066   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19067   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19068   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19069   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19070   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19071   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19072   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19073   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19074   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19075   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19076   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19077   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19078   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19079   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19080   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19081   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19082   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19083   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19084   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19085   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19086   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19087   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19088   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19089   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19090   case X86ISD::VSHL:               return "X86ISD::VSHL";
19091   case X86ISD::VSRL:               return "X86ISD::VSRL";
19092   case X86ISD::VSRA:               return "X86ISD::VSRA";
19093   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19094   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19095   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19096   case X86ISD::CMPP:               return "X86ISD::CMPP";
19097   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19098   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19099   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19100   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19101   case X86ISD::ADD:                return "X86ISD::ADD";
19102   case X86ISD::SUB:                return "X86ISD::SUB";
19103   case X86ISD::ADC:                return "X86ISD::ADC";
19104   case X86ISD::SBB:                return "X86ISD::SBB";
19105   case X86ISD::SMUL:               return "X86ISD::SMUL";
19106   case X86ISD::UMUL:               return "X86ISD::UMUL";
19107   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19108   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19109   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19110   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19111   case X86ISD::INC:                return "X86ISD::INC";
19112   case X86ISD::DEC:                return "X86ISD::DEC";
19113   case X86ISD::OR:                 return "X86ISD::OR";
19114   case X86ISD::XOR:                return "X86ISD::XOR";
19115   case X86ISD::AND:                return "X86ISD::AND";
19116   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19117   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19118   case X86ISD::PTEST:              return "X86ISD::PTEST";
19119   case X86ISD::TESTP:              return "X86ISD::TESTP";
19120   case X86ISD::TESTM:              return "X86ISD::TESTM";
19121   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19122   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19123   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19124   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19125   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19126   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19127   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19128   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19129   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19130   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19131   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19132   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19133   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19134   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19135   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19136   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19137   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19138   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19139   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19140   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19141   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19142   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19143   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19144   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19145   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19146   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19147   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19148   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19149   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19150   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19151   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19152   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19153   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19154   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19155   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19156   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19157   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19158   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19159   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19160   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19161   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19162   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19163   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19164   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19165   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19166   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19167   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19168   case X86ISD::SAHF:               return "X86ISD::SAHF";
19169   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19170   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19171   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19172   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19173   case X86ISD::FMADD:              return "X86ISD::FMADD";
19174   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19175   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19176   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19177   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19178   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19179   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19180   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19181   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19182   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19183   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19184   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19185   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19186   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19187   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19188   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19189   case X86ISD::XTEST:              return "X86ISD::XTEST";
19190   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19191   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19192   case X86ISD::SELECT:             return "X86ISD::SELECT";
19193   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19194   case X86ISD::RCP28:              return "X86ISD::RCP28";
19195   case X86ISD::EXP2:               return "X86ISD::EXP2";
19196   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19197   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19198   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19199   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19200   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19201   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19202   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19203   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19204   case X86ISD::ADDS:               return "X86ISD::ADDS";
19205   case X86ISD::SUBS:               return "X86ISD::SUBS";
19206   case X86ISD::AVG:                return "X86ISD::AVG";
19207   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19208   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19209   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19210   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19211   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19212   }
19213   return nullptr;
19214 }
19215
19216 // isLegalAddressingMode - Return true if the addressing mode represented
19217 // by AM is legal for this target, for a load/store of the specified type.
19218 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19219                                               const AddrMode &AM, Type *Ty,
19220                                               unsigned AS) const {
19221   // X86 supports extremely general addressing modes.
19222   CodeModel::Model M = getTargetMachine().getCodeModel();
19223   Reloc::Model R = getTargetMachine().getRelocationModel();
19224
19225   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19226   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19227     return false;
19228
19229   if (AM.BaseGV) {
19230     unsigned GVFlags =
19231       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19232
19233     // If a reference to this global requires an extra load, we can't fold it.
19234     if (isGlobalStubReference(GVFlags))
19235       return false;
19236
19237     // If BaseGV requires a register for the PIC base, we cannot also have a
19238     // BaseReg specified.
19239     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19240       return false;
19241
19242     // If lower 4G is not available, then we must use rip-relative addressing.
19243     if ((M != CodeModel::Small || R != Reloc::Static) &&
19244         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19245       return false;
19246   }
19247
19248   switch (AM.Scale) {
19249   case 0:
19250   case 1:
19251   case 2:
19252   case 4:
19253   case 8:
19254     // These scales always work.
19255     break;
19256   case 3:
19257   case 5:
19258   case 9:
19259     // These scales are formed with basereg+scalereg.  Only accept if there is
19260     // no basereg yet.
19261     if (AM.HasBaseReg)
19262       return false;
19263     break;
19264   default:  // Other stuff never works.
19265     return false;
19266   }
19267
19268   return true;
19269 }
19270
19271 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19272   unsigned Bits = Ty->getScalarSizeInBits();
19273
19274   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19275   // particularly cheaper than those without.
19276   if (Bits == 8)
19277     return false;
19278
19279   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19280   // variable shifts just as cheap as scalar ones.
19281   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19282     return false;
19283
19284   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19285   // fully general vector.
19286   return true;
19287 }
19288
19289 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19290   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19291     return false;
19292   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19293   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19294   return NumBits1 > NumBits2;
19295 }
19296
19297 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19298   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19299     return false;
19300
19301   if (!isTypeLegal(EVT::getEVT(Ty1)))
19302     return false;
19303
19304   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19305
19306   // Assuming the caller doesn't have a zeroext or signext return parameter,
19307   // truncation all the way down to i1 is valid.
19308   return true;
19309 }
19310
19311 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19312   return isInt<32>(Imm);
19313 }
19314
19315 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19316   // Can also use sub to handle negated immediates.
19317   return isInt<32>(Imm);
19318 }
19319
19320 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19321   if (!VT1.isInteger() || !VT2.isInteger())
19322     return false;
19323   unsigned NumBits1 = VT1.getSizeInBits();
19324   unsigned NumBits2 = VT2.getSizeInBits();
19325   return NumBits1 > NumBits2;
19326 }
19327
19328 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19329   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19330   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19331 }
19332
19333 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19334   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19335   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19336 }
19337
19338 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19339   EVT VT1 = Val.getValueType();
19340   if (isZExtFree(VT1, VT2))
19341     return true;
19342
19343   if (Val.getOpcode() != ISD::LOAD)
19344     return false;
19345
19346   if (!VT1.isSimple() || !VT1.isInteger() ||
19347       !VT2.isSimple() || !VT2.isInteger())
19348     return false;
19349
19350   switch (VT1.getSimpleVT().SimpleTy) {
19351   default: break;
19352   case MVT::i8:
19353   case MVT::i16:
19354   case MVT::i32:
19355     // X86 has 8, 16, and 32-bit zero-extending loads.
19356     return true;
19357   }
19358
19359   return false;
19360 }
19361
19362 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19363
19364 bool
19365 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19366   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19367     return false;
19368
19369   VT = VT.getScalarType();
19370
19371   if (!VT.isSimple())
19372     return false;
19373
19374   switch (VT.getSimpleVT().SimpleTy) {
19375   case MVT::f32:
19376   case MVT::f64:
19377     return true;
19378   default:
19379     break;
19380   }
19381
19382   return false;
19383 }
19384
19385 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19386   // i16 instructions are longer (0x66 prefix) and potentially slower.
19387   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19388 }
19389
19390 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19391 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19392 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19393 /// are assumed to be legal.
19394 bool
19395 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19396                                       EVT VT) const {
19397   if (!VT.isSimple())
19398     return false;
19399
19400   // Not for i1 vectors
19401   if (VT.getScalarType() == MVT::i1)
19402     return false;
19403
19404   // Very little shuffling can be done for 64-bit vectors right now.
19405   if (VT.getSizeInBits() == 64)
19406     return false;
19407
19408   // We only care that the types being shuffled are legal. The lowering can
19409   // handle any possible shuffle mask that results.
19410   return isTypeLegal(VT.getSimpleVT());
19411 }
19412
19413 bool
19414 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19415                                           EVT VT) const {
19416   // Just delegate to the generic legality, clear masks aren't special.
19417   return isShuffleMaskLegal(Mask, VT);
19418 }
19419
19420 //===----------------------------------------------------------------------===//
19421 //                           X86 Scheduler Hooks
19422 //===----------------------------------------------------------------------===//
19423
19424 /// Utility function to emit xbegin specifying the start of an RTM region.
19425 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19426                                      const TargetInstrInfo *TII) {
19427   DebugLoc DL = MI->getDebugLoc();
19428
19429   const BasicBlock *BB = MBB->getBasicBlock();
19430   MachineFunction::iterator I = MBB;
19431   ++I;
19432
19433   // For the v = xbegin(), we generate
19434   //
19435   // thisMBB:
19436   //  xbegin sinkMBB
19437   //
19438   // mainMBB:
19439   //  eax = -1
19440   //
19441   // sinkMBB:
19442   //  v = eax
19443
19444   MachineBasicBlock *thisMBB = MBB;
19445   MachineFunction *MF = MBB->getParent();
19446   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19447   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19448   MF->insert(I, mainMBB);
19449   MF->insert(I, sinkMBB);
19450
19451   // Transfer the remainder of BB and its successor edges to sinkMBB.
19452   sinkMBB->splice(sinkMBB->begin(), MBB,
19453                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19454   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19455
19456   // thisMBB:
19457   //  xbegin sinkMBB
19458   //  # fallthrough to mainMBB
19459   //  # abortion to sinkMBB
19460   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19461   thisMBB->addSuccessor(mainMBB);
19462   thisMBB->addSuccessor(sinkMBB);
19463
19464   // mainMBB:
19465   //  EAX = -1
19466   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19467   mainMBB->addSuccessor(sinkMBB);
19468
19469   // sinkMBB:
19470   // EAX is live into the sinkMBB
19471   sinkMBB->addLiveIn(X86::EAX);
19472   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19473           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19474     .addReg(X86::EAX);
19475
19476   MI->eraseFromParent();
19477   return sinkMBB;
19478 }
19479
19480 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19481 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19482 // in the .td file.
19483 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19484                                        const TargetInstrInfo *TII) {
19485   unsigned Opc;
19486   switch (MI->getOpcode()) {
19487   default: llvm_unreachable("illegal opcode!");
19488   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19489   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19490   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19491   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19492   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19493   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19494   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19495   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19496   }
19497
19498   DebugLoc dl = MI->getDebugLoc();
19499   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19500
19501   unsigned NumArgs = MI->getNumOperands();
19502   for (unsigned i = 1; i < NumArgs; ++i) {
19503     MachineOperand &Op = MI->getOperand(i);
19504     if (!(Op.isReg() && Op.isImplicit()))
19505       MIB.addOperand(Op);
19506   }
19507   if (MI->hasOneMemOperand())
19508     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19509
19510   BuildMI(*BB, MI, dl,
19511     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19512     .addReg(X86::XMM0);
19513
19514   MI->eraseFromParent();
19515   return BB;
19516 }
19517
19518 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19519 // defs in an instruction pattern
19520 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19521                                        const TargetInstrInfo *TII) {
19522   unsigned Opc;
19523   switch (MI->getOpcode()) {
19524   default: llvm_unreachable("illegal opcode!");
19525   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19526   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19527   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19528   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19529   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19530   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19531   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19532   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19533   }
19534
19535   DebugLoc dl = MI->getDebugLoc();
19536   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19537
19538   unsigned NumArgs = MI->getNumOperands(); // remove the results
19539   for (unsigned i = 1; i < NumArgs; ++i) {
19540     MachineOperand &Op = MI->getOperand(i);
19541     if (!(Op.isReg() && Op.isImplicit()))
19542       MIB.addOperand(Op);
19543   }
19544   if (MI->hasOneMemOperand())
19545     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19546
19547   BuildMI(*BB, MI, dl,
19548     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19549     .addReg(X86::ECX);
19550
19551   MI->eraseFromParent();
19552   return BB;
19553 }
19554
19555 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19556                                       const X86Subtarget *Subtarget) {
19557   DebugLoc dl = MI->getDebugLoc();
19558   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19559   // Address into RAX/EAX, other two args into ECX, EDX.
19560   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19561   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19562   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19563   for (int i = 0; i < X86::AddrNumOperands; ++i)
19564     MIB.addOperand(MI->getOperand(i));
19565
19566   unsigned ValOps = X86::AddrNumOperands;
19567   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19568     .addReg(MI->getOperand(ValOps).getReg());
19569   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19570     .addReg(MI->getOperand(ValOps+1).getReg());
19571
19572   // The instruction doesn't actually take any operands though.
19573   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19574
19575   MI->eraseFromParent(); // The pseudo is gone now.
19576   return BB;
19577 }
19578
19579 MachineBasicBlock *
19580 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19581                                                  MachineBasicBlock *MBB) const {
19582   // Emit va_arg instruction on X86-64.
19583
19584   // Operands to this pseudo-instruction:
19585   // 0  ) Output        : destination address (reg)
19586   // 1-5) Input         : va_list address (addr, i64mem)
19587   // 6  ) ArgSize       : Size (in bytes) of vararg type
19588   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19589   // 8  ) Align         : Alignment of type
19590   // 9  ) EFLAGS (implicit-def)
19591
19592   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19593   static_assert(X86::AddrNumOperands == 5,
19594                 "VAARG_64 assumes 5 address operands");
19595
19596   unsigned DestReg = MI->getOperand(0).getReg();
19597   MachineOperand &Base = MI->getOperand(1);
19598   MachineOperand &Scale = MI->getOperand(2);
19599   MachineOperand &Index = MI->getOperand(3);
19600   MachineOperand &Disp = MI->getOperand(4);
19601   MachineOperand &Segment = MI->getOperand(5);
19602   unsigned ArgSize = MI->getOperand(6).getImm();
19603   unsigned ArgMode = MI->getOperand(7).getImm();
19604   unsigned Align = MI->getOperand(8).getImm();
19605
19606   // Memory Reference
19607   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19608   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19609   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19610
19611   // Machine Information
19612   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19613   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19614   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19615   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19616   DebugLoc DL = MI->getDebugLoc();
19617
19618   // struct va_list {
19619   //   i32   gp_offset
19620   //   i32   fp_offset
19621   //   i64   overflow_area (address)
19622   //   i64   reg_save_area (address)
19623   // }
19624   // sizeof(va_list) = 24
19625   // alignment(va_list) = 8
19626
19627   unsigned TotalNumIntRegs = 6;
19628   unsigned TotalNumXMMRegs = 8;
19629   bool UseGPOffset = (ArgMode == 1);
19630   bool UseFPOffset = (ArgMode == 2);
19631   unsigned MaxOffset = TotalNumIntRegs * 8 +
19632                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19633
19634   /* Align ArgSize to a multiple of 8 */
19635   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19636   bool NeedsAlign = (Align > 8);
19637
19638   MachineBasicBlock *thisMBB = MBB;
19639   MachineBasicBlock *overflowMBB;
19640   MachineBasicBlock *offsetMBB;
19641   MachineBasicBlock *endMBB;
19642
19643   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19644   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19645   unsigned OffsetReg = 0;
19646
19647   if (!UseGPOffset && !UseFPOffset) {
19648     // If we only pull from the overflow region, we don't create a branch.
19649     // We don't need to alter control flow.
19650     OffsetDestReg = 0; // unused
19651     OverflowDestReg = DestReg;
19652
19653     offsetMBB = nullptr;
19654     overflowMBB = thisMBB;
19655     endMBB = thisMBB;
19656   } else {
19657     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19658     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19659     // If not, pull from overflow_area. (branch to overflowMBB)
19660     //
19661     //       thisMBB
19662     //         |     .
19663     //         |        .
19664     //     offsetMBB   overflowMBB
19665     //         |        .
19666     //         |     .
19667     //        endMBB
19668
19669     // Registers for the PHI in endMBB
19670     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19671     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19672
19673     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19674     MachineFunction *MF = MBB->getParent();
19675     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19676     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19677     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19678
19679     MachineFunction::iterator MBBIter = MBB;
19680     ++MBBIter;
19681
19682     // Insert the new basic blocks
19683     MF->insert(MBBIter, offsetMBB);
19684     MF->insert(MBBIter, overflowMBB);
19685     MF->insert(MBBIter, endMBB);
19686
19687     // Transfer the remainder of MBB and its successor edges to endMBB.
19688     endMBB->splice(endMBB->begin(), thisMBB,
19689                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19690     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19691
19692     // Make offsetMBB and overflowMBB successors of thisMBB
19693     thisMBB->addSuccessor(offsetMBB);
19694     thisMBB->addSuccessor(overflowMBB);
19695
19696     // endMBB is a successor of both offsetMBB and overflowMBB
19697     offsetMBB->addSuccessor(endMBB);
19698     overflowMBB->addSuccessor(endMBB);
19699
19700     // Load the offset value into a register
19701     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19702     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19703       .addOperand(Base)
19704       .addOperand(Scale)
19705       .addOperand(Index)
19706       .addDisp(Disp, UseFPOffset ? 4 : 0)
19707       .addOperand(Segment)
19708       .setMemRefs(MMOBegin, MMOEnd);
19709
19710     // Check if there is enough room left to pull this argument.
19711     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19712       .addReg(OffsetReg)
19713       .addImm(MaxOffset + 8 - ArgSizeA8);
19714
19715     // Branch to "overflowMBB" if offset >= max
19716     // Fall through to "offsetMBB" otherwise
19717     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19718       .addMBB(overflowMBB);
19719   }
19720
19721   // In offsetMBB, emit code to use the reg_save_area.
19722   if (offsetMBB) {
19723     assert(OffsetReg != 0);
19724
19725     // Read the reg_save_area address.
19726     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19727     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19728       .addOperand(Base)
19729       .addOperand(Scale)
19730       .addOperand(Index)
19731       .addDisp(Disp, 16)
19732       .addOperand(Segment)
19733       .setMemRefs(MMOBegin, MMOEnd);
19734
19735     // Zero-extend the offset
19736     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19737       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19738         .addImm(0)
19739         .addReg(OffsetReg)
19740         .addImm(X86::sub_32bit);
19741
19742     // Add the offset to the reg_save_area to get the final address.
19743     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19744       .addReg(OffsetReg64)
19745       .addReg(RegSaveReg);
19746
19747     // Compute the offset for the next argument
19748     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19749     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19750       .addReg(OffsetReg)
19751       .addImm(UseFPOffset ? 16 : 8);
19752
19753     // Store it back into the va_list.
19754     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19755       .addOperand(Base)
19756       .addOperand(Scale)
19757       .addOperand(Index)
19758       .addDisp(Disp, UseFPOffset ? 4 : 0)
19759       .addOperand(Segment)
19760       .addReg(NextOffsetReg)
19761       .setMemRefs(MMOBegin, MMOEnd);
19762
19763     // Jump to endMBB
19764     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19765       .addMBB(endMBB);
19766   }
19767
19768   //
19769   // Emit code to use overflow area
19770   //
19771
19772   // Load the overflow_area address into a register.
19773   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19774   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19775     .addOperand(Base)
19776     .addOperand(Scale)
19777     .addOperand(Index)
19778     .addDisp(Disp, 8)
19779     .addOperand(Segment)
19780     .setMemRefs(MMOBegin, MMOEnd);
19781
19782   // If we need to align it, do so. Otherwise, just copy the address
19783   // to OverflowDestReg.
19784   if (NeedsAlign) {
19785     // Align the overflow address
19786     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19787     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19788
19789     // aligned_addr = (addr + (align-1)) & ~(align-1)
19790     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19791       .addReg(OverflowAddrReg)
19792       .addImm(Align-1);
19793
19794     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19795       .addReg(TmpReg)
19796       .addImm(~(uint64_t)(Align-1));
19797   } else {
19798     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19799       .addReg(OverflowAddrReg);
19800   }
19801
19802   // Compute the next overflow address after this argument.
19803   // (the overflow address should be kept 8-byte aligned)
19804   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19805   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19806     .addReg(OverflowDestReg)
19807     .addImm(ArgSizeA8);
19808
19809   // Store the new overflow address.
19810   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19811     .addOperand(Base)
19812     .addOperand(Scale)
19813     .addOperand(Index)
19814     .addDisp(Disp, 8)
19815     .addOperand(Segment)
19816     .addReg(NextAddrReg)
19817     .setMemRefs(MMOBegin, MMOEnd);
19818
19819   // If we branched, emit the PHI to the front of endMBB.
19820   if (offsetMBB) {
19821     BuildMI(*endMBB, endMBB->begin(), DL,
19822             TII->get(X86::PHI), DestReg)
19823       .addReg(OffsetDestReg).addMBB(offsetMBB)
19824       .addReg(OverflowDestReg).addMBB(overflowMBB);
19825   }
19826
19827   // Erase the pseudo instruction
19828   MI->eraseFromParent();
19829
19830   return endMBB;
19831 }
19832
19833 MachineBasicBlock *
19834 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19835                                                  MachineInstr *MI,
19836                                                  MachineBasicBlock *MBB) const {
19837   // Emit code to save XMM registers to the stack. The ABI says that the
19838   // number of registers to save is given in %al, so it's theoretically
19839   // possible to do an indirect jump trick to avoid saving all of them,
19840   // however this code takes a simpler approach and just executes all
19841   // of the stores if %al is non-zero. It's less code, and it's probably
19842   // easier on the hardware branch predictor, and stores aren't all that
19843   // expensive anyway.
19844
19845   // Create the new basic blocks. One block contains all the XMM stores,
19846   // and one block is the final destination regardless of whether any
19847   // stores were performed.
19848   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19849   MachineFunction *F = MBB->getParent();
19850   MachineFunction::iterator MBBIter = MBB;
19851   ++MBBIter;
19852   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19853   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19854   F->insert(MBBIter, XMMSaveMBB);
19855   F->insert(MBBIter, EndMBB);
19856
19857   // Transfer the remainder of MBB and its successor edges to EndMBB.
19858   EndMBB->splice(EndMBB->begin(), MBB,
19859                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19860   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19861
19862   // The original block will now fall through to the XMM save block.
19863   MBB->addSuccessor(XMMSaveMBB);
19864   // The XMMSaveMBB will fall through to the end block.
19865   XMMSaveMBB->addSuccessor(EndMBB);
19866
19867   // Now add the instructions.
19868   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19869   DebugLoc DL = MI->getDebugLoc();
19870
19871   unsigned CountReg = MI->getOperand(0).getReg();
19872   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19873   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19874
19875   if (!Subtarget->isTargetWin64()) {
19876     // If %al is 0, branch around the XMM save block.
19877     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19878     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19879     MBB->addSuccessor(EndMBB);
19880   }
19881
19882   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19883   // that was just emitted, but clearly shouldn't be "saved".
19884   assert((MI->getNumOperands() <= 3 ||
19885           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19886           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19887          && "Expected last argument to be EFLAGS");
19888   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19889   // In the XMM save block, save all the XMM argument registers.
19890   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19891     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19892     MachineMemOperand *MMO =
19893       F->getMachineMemOperand(
19894           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19895         MachineMemOperand::MOStore,
19896         /*Size=*/16, /*Align=*/16);
19897     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19898       .addFrameIndex(RegSaveFrameIndex)
19899       .addImm(/*Scale=*/1)
19900       .addReg(/*IndexReg=*/0)
19901       .addImm(/*Disp=*/Offset)
19902       .addReg(/*Segment=*/0)
19903       .addReg(MI->getOperand(i).getReg())
19904       .addMemOperand(MMO);
19905   }
19906
19907   MI->eraseFromParent();   // The pseudo instruction is gone now.
19908
19909   return EndMBB;
19910 }
19911
19912 // The EFLAGS operand of SelectItr might be missing a kill marker
19913 // because there were multiple uses of EFLAGS, and ISel didn't know
19914 // which to mark. Figure out whether SelectItr should have had a
19915 // kill marker, and set it if it should. Returns the correct kill
19916 // marker value.
19917 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19918                                      MachineBasicBlock* BB,
19919                                      const TargetRegisterInfo* TRI) {
19920   // Scan forward through BB for a use/def of EFLAGS.
19921   MachineBasicBlock::iterator miI(std::next(SelectItr));
19922   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19923     const MachineInstr& mi = *miI;
19924     if (mi.readsRegister(X86::EFLAGS))
19925       return false;
19926     if (mi.definesRegister(X86::EFLAGS))
19927       break; // Should have kill-flag - update below.
19928   }
19929
19930   // If we hit the end of the block, check whether EFLAGS is live into a
19931   // successor.
19932   if (miI == BB->end()) {
19933     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19934                                           sEnd = BB->succ_end();
19935          sItr != sEnd; ++sItr) {
19936       MachineBasicBlock* succ = *sItr;
19937       if (succ->isLiveIn(X86::EFLAGS))
19938         return false;
19939     }
19940   }
19941
19942   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19943   // out. SelectMI should have a kill flag on EFLAGS.
19944   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19945   return true;
19946 }
19947
19948 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
19949 // together with other CMOV pseudo-opcodes into a single basic-block with
19950 // conditional jump around it.
19951 static bool isCMOVPseudo(MachineInstr *MI) {
19952   switch (MI->getOpcode()) {
19953   case X86::CMOV_FR32:
19954   case X86::CMOV_FR64:
19955   case X86::CMOV_GR8:
19956   case X86::CMOV_GR16:
19957   case X86::CMOV_GR32:
19958   case X86::CMOV_RFP32:
19959   case X86::CMOV_RFP64:
19960   case X86::CMOV_RFP80:
19961   case X86::CMOV_V2F64:
19962   case X86::CMOV_V2I64:
19963   case X86::CMOV_V4F32:
19964   case X86::CMOV_V4F64:
19965   case X86::CMOV_V4I64:
19966   case X86::CMOV_V16F32:
19967   case X86::CMOV_V8F32:
19968   case X86::CMOV_V8F64:
19969   case X86::CMOV_V8I64:
19970   case X86::CMOV_V8I1:
19971   case X86::CMOV_V16I1:
19972   case X86::CMOV_V32I1:
19973   case X86::CMOV_V64I1:
19974     return true;
19975
19976   default:
19977     return false;
19978   }
19979 }
19980
19981 MachineBasicBlock *
19982 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19983                                      MachineBasicBlock *BB) const {
19984   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19985   DebugLoc DL = MI->getDebugLoc();
19986
19987   // To "insert" a SELECT_CC instruction, we actually have to insert the
19988   // diamond control-flow pattern.  The incoming instruction knows the
19989   // destination vreg to set, the condition code register to branch on, the
19990   // true/false values to select between, and a branch opcode to use.
19991   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19992   MachineFunction::iterator It = BB;
19993   ++It;
19994
19995   //  thisMBB:
19996   //  ...
19997   //   TrueVal = ...
19998   //   cmpTY ccX, r1, r2
19999   //   bCC copy1MBB
20000   //   fallthrough --> copy0MBB
20001   MachineBasicBlock *thisMBB = BB;
20002   MachineFunction *F = BB->getParent();
20003
20004   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20005   // as described above, by inserting a BB, and then making a PHI at the join
20006   // point to select the true and false operands of the CMOV in the PHI.
20007   //
20008   // The code also handles two different cases of multiple CMOV opcodes
20009   // in a row.
20010   //
20011   // Case 1:
20012   // In this case, there are multiple CMOVs in a row, all which are based on
20013   // the same condition setting (or the exact opposite condition setting).
20014   // In this case we can lower all the CMOVs using a single inserted BB, and
20015   // then make a number of PHIs at the join point to model the CMOVs. The only
20016   // trickiness here, is that in a case like:
20017   //
20018   // t2 = CMOV cond1 t1, f1
20019   // t3 = CMOV cond1 t2, f2
20020   //
20021   // when rewriting this into PHIs, we have to perform some renaming on the
20022   // temps since you cannot have a PHI operand refer to a PHI result earlier
20023   // in the same block.  The "simple" but wrong lowering would be:
20024   //
20025   // t2 = PHI t1(BB1), f1(BB2)
20026   // t3 = PHI t2(BB1), f2(BB2)
20027   //
20028   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20029   // renaming is to note that on the path through BB1, t2 is really just a
20030   // copy of t1, and do that renaming, properly generating:
20031   //
20032   // t2 = PHI t1(BB1), f1(BB2)
20033   // t3 = PHI t1(BB1), f2(BB2)
20034   //
20035   // Case 2, we lower cascaded CMOVs such as
20036   //
20037   //   (CMOV (CMOV F, T, cc1), T, cc2)
20038   //
20039   // to two successives branches.  For that, we look for another CMOV as the
20040   // following instruction.
20041   //
20042   // Without this, we would add a PHI between the two jumps, which ends up
20043   // creating a few copies all around. For instance, for
20044   //
20045   //    (sitofp (zext (fcmp une)))
20046   //
20047   // we would generate:
20048   //
20049   //         ucomiss %xmm1, %xmm0
20050   //         movss  <1.0f>, %xmm0
20051   //         movaps  %xmm0, %xmm1
20052   //         jne     .LBB5_2
20053   //         xorps   %xmm1, %xmm1
20054   // .LBB5_2:
20055   //         jp      .LBB5_4
20056   //         movaps  %xmm1, %xmm0
20057   // .LBB5_4:
20058   //         retq
20059   //
20060   // because this custom-inserter would have generated:
20061   //
20062   //   A
20063   //   | \
20064   //   |  B
20065   //   | /
20066   //   C
20067   //   | \
20068   //   |  D
20069   //   | /
20070   //   E
20071   //
20072   // A: X = ...; Y = ...
20073   // B: empty
20074   // C: Z = PHI [X, A], [Y, B]
20075   // D: empty
20076   // E: PHI [X, C], [Z, D]
20077   //
20078   // If we lower both CMOVs in a single step, we can instead generate:
20079   //
20080   //   A
20081   //   | \
20082   //   |  C
20083   //   | /|
20084   //   |/ |
20085   //   |  |
20086   //   |  D
20087   //   | /
20088   //   E
20089   //
20090   // A: X = ...; Y = ...
20091   // D: empty
20092   // E: PHI [X, A], [X, C], [Y, D]
20093   //
20094   // Which, in our sitofp/fcmp example, gives us something like:
20095   //
20096   //         ucomiss %xmm1, %xmm0
20097   //         movss  <1.0f>, %xmm0
20098   //         jne     .LBB5_4
20099   //         jp      .LBB5_4
20100   //         xorps   %xmm0, %xmm0
20101   // .LBB5_4:
20102   //         retq
20103   //
20104   MachineInstr *CascadedCMOV = nullptr;
20105   MachineInstr *LastCMOV = MI;
20106   X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20107   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20108   MachineBasicBlock::iterator NextMIIt =
20109       std::next(MachineBasicBlock::iterator(MI));
20110
20111   // Check for case 1, where there are multiple CMOVs with the same condition
20112   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
20113   // number of jumps the most.
20114
20115   if (isCMOVPseudo(MI)) {
20116     // See if we have a string of CMOVS with the same condition.
20117     while (NextMIIt != BB->end() &&
20118            isCMOVPseudo(NextMIIt) &&
20119            (NextMIIt->getOperand(3).getImm() == CC ||
20120             NextMIIt->getOperand(3).getImm() == OppCC)) {
20121       LastCMOV = &*NextMIIt;
20122       ++NextMIIt;
20123     }
20124   }
20125
20126   // This checks for case 2, but only do this if we didn't already find
20127   // case 1, as indicated by LastCMOV == MI.
20128   if (LastCMOV == MI &&
20129       NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20130       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20131       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20132     CascadedCMOV = &*NextMIIt;
20133   }
20134
20135   MachineBasicBlock *jcc1MBB = nullptr;
20136
20137   // If we have a cascaded CMOV, we lower it to two successive branches to
20138   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20139   if (CascadedCMOV) {
20140     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20141     F->insert(It, jcc1MBB);
20142     jcc1MBB->addLiveIn(X86::EFLAGS);
20143   }
20144
20145   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20146   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20147   F->insert(It, copy0MBB);
20148   F->insert(It, sinkMBB);
20149
20150   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20151   // live into the sink and copy blocks.
20152   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20153
20154   MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20155   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20156       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20157     copy0MBB->addLiveIn(X86::EFLAGS);
20158     sinkMBB->addLiveIn(X86::EFLAGS);
20159   }
20160
20161   // Transfer the remainder of BB and its successor edges to sinkMBB.
20162   sinkMBB->splice(sinkMBB->begin(), BB,
20163                   std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20164   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20165
20166   // Add the true and fallthrough blocks as its successors.
20167   if (CascadedCMOV) {
20168     // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20169     BB->addSuccessor(jcc1MBB);
20170
20171     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20172     // jump to the sinkMBB.
20173     jcc1MBB->addSuccessor(copy0MBB);
20174     jcc1MBB->addSuccessor(sinkMBB);
20175   } else {
20176     BB->addSuccessor(copy0MBB);
20177   }
20178
20179   // The true block target of the first (or only) branch is always sinkMBB.
20180   BB->addSuccessor(sinkMBB);
20181
20182   // Create the conditional branch instruction.
20183   unsigned Opc = X86::GetCondBranchFromCond(CC);
20184   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20185
20186   if (CascadedCMOV) {
20187     unsigned Opc2 = X86::GetCondBranchFromCond(
20188         (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20189     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20190   }
20191
20192   //  copy0MBB:
20193   //   %FalseValue = ...
20194   //   # fallthrough to sinkMBB
20195   copy0MBB->addSuccessor(sinkMBB);
20196
20197   //  sinkMBB:
20198   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20199   //  ...
20200   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20201   MachineBasicBlock::iterator MIItEnd =
20202     std::next(MachineBasicBlock::iterator(LastCMOV));
20203   MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20204   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20205   MachineInstrBuilder MIB;
20206
20207   // As we are creating the PHIs, we have to be careful if there is more than
20208   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
20209   // PHIs have to reference the individual true/false inputs from earlier PHIs.
20210   // That also means that PHI construction must work forward from earlier to
20211   // later, and that the code must maintain a mapping from earlier PHI's
20212   // destination registers, and the registers that went into the PHI.
20213
20214   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20215     unsigned DestReg = MIIt->getOperand(0).getReg();
20216     unsigned Op1Reg = MIIt->getOperand(1).getReg();
20217     unsigned Op2Reg = MIIt->getOperand(2).getReg();
20218
20219     // If this CMOV we are generating is the opposite condition from
20220     // the jump we generated, then we have to swap the operands for the
20221     // PHI that is going to be generated.
20222     if (MIIt->getOperand(3).getImm() == OppCC)
20223         std::swap(Op1Reg, Op2Reg);
20224
20225     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20226       Op1Reg = RegRewriteTable[Op1Reg].first;
20227
20228     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20229       Op2Reg = RegRewriteTable[Op2Reg].second;
20230
20231     MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20232                   TII->get(X86::PHI), DestReg)
20233           .addReg(Op1Reg).addMBB(copy0MBB)
20234           .addReg(Op2Reg).addMBB(thisMBB);
20235
20236     // Add this PHI to the rewrite table.
20237     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20238   }
20239
20240   // If we have a cascaded CMOV, the second Jcc provides the same incoming
20241   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20242   if (CascadedCMOV) {
20243     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20244     // Copy the PHI result to the register defined by the second CMOV.
20245     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20246             DL, TII->get(TargetOpcode::COPY),
20247             CascadedCMOV->getOperand(0).getReg())
20248         .addReg(MI->getOperand(0).getReg());
20249     CascadedCMOV->eraseFromParent();
20250   }
20251
20252   // Now remove the CMOV(s).
20253   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20254     (MIIt++)->eraseFromParent();
20255
20256   return sinkMBB;
20257 }
20258
20259 MachineBasicBlock *
20260 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20261                                        MachineBasicBlock *BB) const {
20262   // Combine the following atomic floating-point modification pattern:
20263   //   a.store(reg OP a.load(acquire), release)
20264   // Transform them into:
20265   //   OPss (%gpr), %xmm
20266   //   movss %xmm, (%gpr)
20267   // Or sd equivalent for 64-bit operations.
20268   unsigned MOp, FOp;
20269   switch (MI->getOpcode()) {
20270   default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20271   case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20272   case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20273   }
20274   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20275   DebugLoc DL = MI->getDebugLoc();
20276   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20277   unsigned MSrc = MI->getOperand(0).getReg();
20278   unsigned VSrc = MI->getOperand(5).getReg();
20279   MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20280                                 .addReg(/*Base=*/MSrc)
20281                                 .addImm(/*Scale=*/1)
20282                                 .addReg(/*Index=*/0)
20283                                 .addImm(0)
20284                                 .addReg(0);
20285   MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20286                               MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20287                           .addReg(VSrc)
20288                           .addReg(/*Base=*/MSrc)
20289                           .addImm(/*Scale=*/1)
20290                           .addReg(/*Index=*/0)
20291                           .addImm(/*Disp=*/0)
20292                           .addReg(/*Segment=*/0);
20293   MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20294   MI->eraseFromParent(); // The pseudo instruction is gone now.
20295   return BB;
20296 }
20297
20298 MachineBasicBlock *
20299 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20300                                         MachineBasicBlock *BB) const {
20301   MachineFunction *MF = BB->getParent();
20302   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20303   DebugLoc DL = MI->getDebugLoc();
20304   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20305
20306   assert(MF->shouldSplitStack());
20307
20308   const bool Is64Bit = Subtarget->is64Bit();
20309   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20310
20311   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20312   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20313
20314   // BB:
20315   //  ... [Till the alloca]
20316   // If stacklet is not large enough, jump to mallocMBB
20317   //
20318   // bumpMBB:
20319   //  Allocate by subtracting from RSP
20320   //  Jump to continueMBB
20321   //
20322   // mallocMBB:
20323   //  Allocate by call to runtime
20324   //
20325   // continueMBB:
20326   //  ...
20327   //  [rest of original BB]
20328   //
20329
20330   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20331   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20332   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20333
20334   MachineRegisterInfo &MRI = MF->getRegInfo();
20335   const TargetRegisterClass *AddrRegClass =
20336       getRegClassFor(getPointerTy(MF->getDataLayout()));
20337
20338   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20339     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20340     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20341     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20342     sizeVReg = MI->getOperand(1).getReg(),
20343     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20344
20345   MachineFunction::iterator MBBIter = BB;
20346   ++MBBIter;
20347
20348   MF->insert(MBBIter, bumpMBB);
20349   MF->insert(MBBIter, mallocMBB);
20350   MF->insert(MBBIter, continueMBB);
20351
20352   continueMBB->splice(continueMBB->begin(), BB,
20353                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20354   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20355
20356   // Add code to the main basic block to check if the stack limit has been hit,
20357   // and if so, jump to mallocMBB otherwise to bumpMBB.
20358   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20359   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20360     .addReg(tmpSPVReg).addReg(sizeVReg);
20361   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20362     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20363     .addReg(SPLimitVReg);
20364   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20365
20366   // bumpMBB simply decreases the stack pointer, since we know the current
20367   // stacklet has enough space.
20368   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20369     .addReg(SPLimitVReg);
20370   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20371     .addReg(SPLimitVReg);
20372   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20373
20374   // Calls into a routine in libgcc to allocate more space from the heap.
20375   const uint32_t *RegMask =
20376       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20377   if (IsLP64) {
20378     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20379       .addReg(sizeVReg);
20380     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20381       .addExternalSymbol("__morestack_allocate_stack_space")
20382       .addRegMask(RegMask)
20383       .addReg(X86::RDI, RegState::Implicit)
20384       .addReg(X86::RAX, RegState::ImplicitDefine);
20385   } else if (Is64Bit) {
20386     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20387       .addReg(sizeVReg);
20388     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20389       .addExternalSymbol("__morestack_allocate_stack_space")
20390       .addRegMask(RegMask)
20391       .addReg(X86::EDI, RegState::Implicit)
20392       .addReg(X86::EAX, RegState::ImplicitDefine);
20393   } else {
20394     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20395       .addImm(12);
20396     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20397     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20398       .addExternalSymbol("__morestack_allocate_stack_space")
20399       .addRegMask(RegMask)
20400       .addReg(X86::EAX, RegState::ImplicitDefine);
20401   }
20402
20403   if (!Is64Bit)
20404     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20405       .addImm(16);
20406
20407   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20408     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20409   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20410
20411   // Set up the CFG correctly.
20412   BB->addSuccessor(bumpMBB);
20413   BB->addSuccessor(mallocMBB);
20414   mallocMBB->addSuccessor(continueMBB);
20415   bumpMBB->addSuccessor(continueMBB);
20416
20417   // Take care of the PHI nodes.
20418   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20419           MI->getOperand(0).getReg())
20420     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20421     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20422
20423   // Delete the original pseudo instruction.
20424   MI->eraseFromParent();
20425
20426   // And we're done.
20427   return continueMBB;
20428 }
20429
20430 MachineBasicBlock *
20431 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20432                                         MachineBasicBlock *BB) const {
20433   DebugLoc DL = MI->getDebugLoc();
20434
20435   assert(!Subtarget->isTargetMachO());
20436
20437   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20438                                                     DL);
20439
20440   MI->eraseFromParent();   // The pseudo instruction is gone now.
20441   return BB;
20442 }
20443
20444 MachineBasicBlock *
20445 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20446                                       MachineBasicBlock *BB) const {
20447   // This is pretty easy.  We're taking the value that we received from
20448   // our load from the relocation, sticking it in either RDI (x86-64)
20449   // or EAX and doing an indirect call.  The return value will then
20450   // be in the normal return register.
20451   MachineFunction *F = BB->getParent();
20452   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20453   DebugLoc DL = MI->getDebugLoc();
20454
20455   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20456   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20457
20458   // Get a register mask for the lowered call.
20459   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20460   // proper register mask.
20461   const uint32_t *RegMask =
20462       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20463   if (Subtarget->is64Bit()) {
20464     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20465                                       TII->get(X86::MOV64rm), X86::RDI)
20466     .addReg(X86::RIP)
20467     .addImm(0).addReg(0)
20468     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20469                       MI->getOperand(3).getTargetFlags())
20470     .addReg(0);
20471     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20472     addDirectMem(MIB, X86::RDI);
20473     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20474   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20475     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20476                                       TII->get(X86::MOV32rm), X86::EAX)
20477     .addReg(0)
20478     .addImm(0).addReg(0)
20479     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20480                       MI->getOperand(3).getTargetFlags())
20481     .addReg(0);
20482     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20483     addDirectMem(MIB, X86::EAX);
20484     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20485   } else {
20486     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20487                                       TII->get(X86::MOV32rm), X86::EAX)
20488     .addReg(TII->getGlobalBaseReg(F))
20489     .addImm(0).addReg(0)
20490     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20491                       MI->getOperand(3).getTargetFlags())
20492     .addReg(0);
20493     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20494     addDirectMem(MIB, X86::EAX);
20495     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20496   }
20497
20498   MI->eraseFromParent(); // The pseudo instruction is gone now.
20499   return BB;
20500 }
20501
20502 MachineBasicBlock *
20503 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20504                                     MachineBasicBlock *MBB) const {
20505   DebugLoc DL = MI->getDebugLoc();
20506   MachineFunction *MF = MBB->getParent();
20507   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20508   MachineRegisterInfo &MRI = MF->getRegInfo();
20509
20510   const BasicBlock *BB = MBB->getBasicBlock();
20511   MachineFunction::iterator I = MBB;
20512   ++I;
20513
20514   // Memory Reference
20515   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20516   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20517
20518   unsigned DstReg;
20519   unsigned MemOpndSlot = 0;
20520
20521   unsigned CurOp = 0;
20522
20523   DstReg = MI->getOperand(CurOp++).getReg();
20524   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20525   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20526   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20527   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20528
20529   MemOpndSlot = CurOp;
20530
20531   MVT PVT = getPointerTy(MF->getDataLayout());
20532   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20533          "Invalid Pointer Size!");
20534
20535   // For v = setjmp(buf), we generate
20536   //
20537   // thisMBB:
20538   //  buf[LabelOffset] = restoreMBB
20539   //  SjLjSetup restoreMBB
20540   //
20541   // mainMBB:
20542   //  v_main = 0
20543   //
20544   // sinkMBB:
20545   //  v = phi(main, restore)
20546   //
20547   // restoreMBB:
20548   //  if base pointer being used, load it from frame
20549   //  v_restore = 1
20550
20551   MachineBasicBlock *thisMBB = MBB;
20552   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20553   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20554   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20555   MF->insert(I, mainMBB);
20556   MF->insert(I, sinkMBB);
20557   MF->push_back(restoreMBB);
20558
20559   MachineInstrBuilder MIB;
20560
20561   // Transfer the remainder of BB and its successor edges to sinkMBB.
20562   sinkMBB->splice(sinkMBB->begin(), MBB,
20563                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20564   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20565
20566   // thisMBB:
20567   unsigned PtrStoreOpc = 0;
20568   unsigned LabelReg = 0;
20569   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20570   Reloc::Model RM = MF->getTarget().getRelocationModel();
20571   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20572                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20573
20574   // Prepare IP either in reg or imm.
20575   if (!UseImmLabel) {
20576     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20577     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20578     LabelReg = MRI.createVirtualRegister(PtrRC);
20579     if (Subtarget->is64Bit()) {
20580       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20581               .addReg(X86::RIP)
20582               .addImm(0)
20583               .addReg(0)
20584               .addMBB(restoreMBB)
20585               .addReg(0);
20586     } else {
20587       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20588       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20589               .addReg(XII->getGlobalBaseReg(MF))
20590               .addImm(0)
20591               .addReg(0)
20592               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20593               .addReg(0);
20594     }
20595   } else
20596     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20597   // Store IP
20598   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20599   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20600     if (i == X86::AddrDisp)
20601       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20602     else
20603       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20604   }
20605   if (!UseImmLabel)
20606     MIB.addReg(LabelReg);
20607   else
20608     MIB.addMBB(restoreMBB);
20609   MIB.setMemRefs(MMOBegin, MMOEnd);
20610   // Setup
20611   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20612           .addMBB(restoreMBB);
20613
20614   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20615   MIB.addRegMask(RegInfo->getNoPreservedMask());
20616   thisMBB->addSuccessor(mainMBB);
20617   thisMBB->addSuccessor(restoreMBB);
20618
20619   // mainMBB:
20620   //  EAX = 0
20621   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20622   mainMBB->addSuccessor(sinkMBB);
20623
20624   // sinkMBB:
20625   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20626           TII->get(X86::PHI), DstReg)
20627     .addReg(mainDstReg).addMBB(mainMBB)
20628     .addReg(restoreDstReg).addMBB(restoreMBB);
20629
20630   // restoreMBB:
20631   if (RegInfo->hasBasePointer(*MF)) {
20632     const bool Uses64BitFramePtr =
20633         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20634     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20635     X86FI->setRestoreBasePointer(MF);
20636     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20637     unsigned BasePtr = RegInfo->getBaseRegister();
20638     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20639     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20640                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20641       .setMIFlag(MachineInstr::FrameSetup);
20642   }
20643   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20644   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20645   restoreMBB->addSuccessor(sinkMBB);
20646
20647   MI->eraseFromParent();
20648   return sinkMBB;
20649 }
20650
20651 MachineBasicBlock *
20652 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20653                                      MachineBasicBlock *MBB) const {
20654   DebugLoc DL = MI->getDebugLoc();
20655   MachineFunction *MF = MBB->getParent();
20656   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20657   MachineRegisterInfo &MRI = MF->getRegInfo();
20658
20659   // Memory Reference
20660   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20661   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20662
20663   MVT PVT = getPointerTy(MF->getDataLayout());
20664   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20665          "Invalid Pointer Size!");
20666
20667   const TargetRegisterClass *RC =
20668     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20669   unsigned Tmp = MRI.createVirtualRegister(RC);
20670   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20671   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20672   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20673   unsigned SP = RegInfo->getStackRegister();
20674
20675   MachineInstrBuilder MIB;
20676
20677   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20678   const int64_t SPOffset = 2 * PVT.getStoreSize();
20679
20680   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20681   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20682
20683   // Reload FP
20684   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20685   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20686     MIB.addOperand(MI->getOperand(i));
20687   MIB.setMemRefs(MMOBegin, MMOEnd);
20688   // Reload IP
20689   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20690   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20691     if (i == X86::AddrDisp)
20692       MIB.addDisp(MI->getOperand(i), LabelOffset);
20693     else
20694       MIB.addOperand(MI->getOperand(i));
20695   }
20696   MIB.setMemRefs(MMOBegin, MMOEnd);
20697   // Reload SP
20698   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20699   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20700     if (i == X86::AddrDisp)
20701       MIB.addDisp(MI->getOperand(i), SPOffset);
20702     else
20703       MIB.addOperand(MI->getOperand(i));
20704   }
20705   MIB.setMemRefs(MMOBegin, MMOEnd);
20706   // Jump
20707   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20708
20709   MI->eraseFromParent();
20710   return MBB;
20711 }
20712
20713 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20714 // accumulator loops. Writing back to the accumulator allows the coalescer
20715 // to remove extra copies in the loop.
20716 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20717 MachineBasicBlock *
20718 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20719                                  MachineBasicBlock *MBB) const {
20720   MachineOperand &AddendOp = MI->getOperand(3);
20721
20722   // Bail out early if the addend isn't a register - we can't switch these.
20723   if (!AddendOp.isReg())
20724     return MBB;
20725
20726   MachineFunction &MF = *MBB->getParent();
20727   MachineRegisterInfo &MRI = MF.getRegInfo();
20728
20729   // Check whether the addend is defined by a PHI:
20730   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20731   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20732   if (!AddendDef.isPHI())
20733     return MBB;
20734
20735   // Look for the following pattern:
20736   // loop:
20737   //   %addend = phi [%entry, 0], [%loop, %result]
20738   //   ...
20739   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20740
20741   // Replace with:
20742   //   loop:
20743   //   %addend = phi [%entry, 0], [%loop, %result]
20744   //   ...
20745   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20746
20747   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20748     assert(AddendDef.getOperand(i).isReg());
20749     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20750     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20751     if (&PHISrcInst == MI) {
20752       // Found a matching instruction.
20753       unsigned NewFMAOpc = 0;
20754       switch (MI->getOpcode()) {
20755         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20756         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20757         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20758         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20759         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20760         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20761         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20762         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20763         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20764         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20765         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20766         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20767         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20768         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20769         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20770         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20771         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20772         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20773         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20774         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20775
20776         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20777         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20778         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20779         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20780         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20781         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20782         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20783         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20784         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20785         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20786         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20787         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20788         default: llvm_unreachable("Unrecognized FMA variant.");
20789       }
20790
20791       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20792       MachineInstrBuilder MIB =
20793         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20794         .addOperand(MI->getOperand(0))
20795         .addOperand(MI->getOperand(3))
20796         .addOperand(MI->getOperand(2))
20797         .addOperand(MI->getOperand(1));
20798       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20799       MI->eraseFromParent();
20800     }
20801   }
20802
20803   return MBB;
20804 }
20805
20806 MachineBasicBlock *
20807 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20808                                                MachineBasicBlock *BB) const {
20809   switch (MI->getOpcode()) {
20810   default: llvm_unreachable("Unexpected instr type to insert");
20811   case X86::TAILJMPd64:
20812   case X86::TAILJMPr64:
20813   case X86::TAILJMPm64:
20814   case X86::TAILJMPd64_REX:
20815   case X86::TAILJMPr64_REX:
20816   case X86::TAILJMPm64_REX:
20817     llvm_unreachable("TAILJMP64 would not be touched here.");
20818   case X86::TCRETURNdi64:
20819   case X86::TCRETURNri64:
20820   case X86::TCRETURNmi64:
20821     return BB;
20822   case X86::WIN_ALLOCA:
20823     return EmitLoweredWinAlloca(MI, BB);
20824   case X86::SEG_ALLOCA_32:
20825   case X86::SEG_ALLOCA_64:
20826     return EmitLoweredSegAlloca(MI, BB);
20827   case X86::TLSCall_32:
20828   case X86::TLSCall_64:
20829     return EmitLoweredTLSCall(MI, BB);
20830   case X86::CMOV_FR32:
20831   case X86::CMOV_FR64:
20832   case X86::CMOV_GR8:
20833   case X86::CMOV_GR16:
20834   case X86::CMOV_GR32:
20835   case X86::CMOV_RFP32:
20836   case X86::CMOV_RFP64:
20837   case X86::CMOV_RFP80:
20838   case X86::CMOV_V2F64:
20839   case X86::CMOV_V2I64:
20840   case X86::CMOV_V4F32:
20841   case X86::CMOV_V4F64:
20842   case X86::CMOV_V4I64:
20843   case X86::CMOV_V16F32:
20844   case X86::CMOV_V8F32:
20845   case X86::CMOV_V8F64:
20846   case X86::CMOV_V8I64:
20847   case X86::CMOV_V8I1:
20848   case X86::CMOV_V16I1:
20849   case X86::CMOV_V32I1:
20850   case X86::CMOV_V64I1:
20851     return EmitLoweredSelect(MI, BB);
20852
20853   case X86::RELEASE_FADD32mr:
20854   case X86::RELEASE_FADD64mr:
20855     return EmitLoweredAtomicFP(MI, BB);
20856
20857   case X86::FP32_TO_INT16_IN_MEM:
20858   case X86::FP32_TO_INT32_IN_MEM:
20859   case X86::FP32_TO_INT64_IN_MEM:
20860   case X86::FP64_TO_INT16_IN_MEM:
20861   case X86::FP64_TO_INT32_IN_MEM:
20862   case X86::FP64_TO_INT64_IN_MEM:
20863   case X86::FP80_TO_INT16_IN_MEM:
20864   case X86::FP80_TO_INT32_IN_MEM:
20865   case X86::FP80_TO_INT64_IN_MEM: {
20866     MachineFunction *F = BB->getParent();
20867     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20868     DebugLoc DL = MI->getDebugLoc();
20869
20870     // Change the floating point control register to use "round towards zero"
20871     // mode when truncating to an integer value.
20872     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20873     addFrameReference(BuildMI(*BB, MI, DL,
20874                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20875
20876     // Load the old value of the high byte of the control word...
20877     unsigned OldCW =
20878       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20879     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20880                       CWFrameIdx);
20881
20882     // Set the high part to be round to zero...
20883     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20884       .addImm(0xC7F);
20885
20886     // Reload the modified control word now...
20887     addFrameReference(BuildMI(*BB, MI, DL,
20888                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20889
20890     // Restore the memory image of control word to original value
20891     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20892       .addReg(OldCW);
20893
20894     // Get the X86 opcode to use.
20895     unsigned Opc;
20896     switch (MI->getOpcode()) {
20897     default: llvm_unreachable("illegal opcode!");
20898     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20899     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20900     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20901     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20902     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20903     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20904     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20905     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20906     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20907     }
20908
20909     X86AddressMode AM;
20910     MachineOperand &Op = MI->getOperand(0);
20911     if (Op.isReg()) {
20912       AM.BaseType = X86AddressMode::RegBase;
20913       AM.Base.Reg = Op.getReg();
20914     } else {
20915       AM.BaseType = X86AddressMode::FrameIndexBase;
20916       AM.Base.FrameIndex = Op.getIndex();
20917     }
20918     Op = MI->getOperand(1);
20919     if (Op.isImm())
20920       AM.Scale = Op.getImm();
20921     Op = MI->getOperand(2);
20922     if (Op.isImm())
20923       AM.IndexReg = Op.getImm();
20924     Op = MI->getOperand(3);
20925     if (Op.isGlobal()) {
20926       AM.GV = Op.getGlobal();
20927     } else {
20928       AM.Disp = Op.getImm();
20929     }
20930     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20931                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20932
20933     // Reload the original control word now.
20934     addFrameReference(BuildMI(*BB, MI, DL,
20935                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20936
20937     MI->eraseFromParent();   // The pseudo instruction is gone now.
20938     return BB;
20939   }
20940     // String/text processing lowering.
20941   case X86::PCMPISTRM128REG:
20942   case X86::VPCMPISTRM128REG:
20943   case X86::PCMPISTRM128MEM:
20944   case X86::VPCMPISTRM128MEM:
20945   case X86::PCMPESTRM128REG:
20946   case X86::VPCMPESTRM128REG:
20947   case X86::PCMPESTRM128MEM:
20948   case X86::VPCMPESTRM128MEM:
20949     assert(Subtarget->hasSSE42() &&
20950            "Target must have SSE4.2 or AVX features enabled");
20951     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20952
20953   // String/text processing lowering.
20954   case X86::PCMPISTRIREG:
20955   case X86::VPCMPISTRIREG:
20956   case X86::PCMPISTRIMEM:
20957   case X86::VPCMPISTRIMEM:
20958   case X86::PCMPESTRIREG:
20959   case X86::VPCMPESTRIREG:
20960   case X86::PCMPESTRIMEM:
20961   case X86::VPCMPESTRIMEM:
20962     assert(Subtarget->hasSSE42() &&
20963            "Target must have SSE4.2 or AVX features enabled");
20964     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20965
20966   // Thread synchronization.
20967   case X86::MONITOR:
20968     return EmitMonitor(MI, BB, Subtarget);
20969
20970   // xbegin
20971   case X86::XBEGIN:
20972     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20973
20974   case X86::VASTART_SAVE_XMM_REGS:
20975     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20976
20977   case X86::VAARG_64:
20978     return EmitVAARG64WithCustomInserter(MI, BB);
20979
20980   case X86::EH_SjLj_SetJmp32:
20981   case X86::EH_SjLj_SetJmp64:
20982     return emitEHSjLjSetJmp(MI, BB);
20983
20984   case X86::EH_SjLj_LongJmp32:
20985   case X86::EH_SjLj_LongJmp64:
20986     return emitEHSjLjLongJmp(MI, BB);
20987
20988   case TargetOpcode::STATEPOINT:
20989     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20990     // this point in the process.  We diverge later.
20991     return emitPatchPoint(MI, BB);
20992
20993   case TargetOpcode::STACKMAP:
20994   case TargetOpcode::PATCHPOINT:
20995     return emitPatchPoint(MI, BB);
20996
20997   case X86::VFMADDPDr213r:
20998   case X86::VFMADDPSr213r:
20999   case X86::VFMADDSDr213r:
21000   case X86::VFMADDSSr213r:
21001   case X86::VFMSUBPDr213r:
21002   case X86::VFMSUBPSr213r:
21003   case X86::VFMSUBSDr213r:
21004   case X86::VFMSUBSSr213r:
21005   case X86::VFNMADDPDr213r:
21006   case X86::VFNMADDPSr213r:
21007   case X86::VFNMADDSDr213r:
21008   case X86::VFNMADDSSr213r:
21009   case X86::VFNMSUBPDr213r:
21010   case X86::VFNMSUBPSr213r:
21011   case X86::VFNMSUBSDr213r:
21012   case X86::VFNMSUBSSr213r:
21013   case X86::VFMADDSUBPDr213r:
21014   case X86::VFMADDSUBPSr213r:
21015   case X86::VFMSUBADDPDr213r:
21016   case X86::VFMSUBADDPSr213r:
21017   case X86::VFMADDPDr213rY:
21018   case X86::VFMADDPSr213rY:
21019   case X86::VFMSUBPDr213rY:
21020   case X86::VFMSUBPSr213rY:
21021   case X86::VFNMADDPDr213rY:
21022   case X86::VFNMADDPSr213rY:
21023   case X86::VFNMSUBPDr213rY:
21024   case X86::VFNMSUBPSr213rY:
21025   case X86::VFMADDSUBPDr213rY:
21026   case X86::VFMADDSUBPSr213rY:
21027   case X86::VFMSUBADDPDr213rY:
21028   case X86::VFMSUBADDPSr213rY:
21029     return emitFMA3Instr(MI, BB);
21030   }
21031 }
21032
21033 //===----------------------------------------------------------------------===//
21034 //                           X86 Optimization Hooks
21035 //===----------------------------------------------------------------------===//
21036
21037 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21038                                                       APInt &KnownZero,
21039                                                       APInt &KnownOne,
21040                                                       const SelectionDAG &DAG,
21041                                                       unsigned Depth) const {
21042   unsigned BitWidth = KnownZero.getBitWidth();
21043   unsigned Opc = Op.getOpcode();
21044   assert((Opc >= ISD::BUILTIN_OP_END ||
21045           Opc == ISD::INTRINSIC_WO_CHAIN ||
21046           Opc == ISD::INTRINSIC_W_CHAIN ||
21047           Opc == ISD::INTRINSIC_VOID) &&
21048          "Should use MaskedValueIsZero if you don't know whether Op"
21049          " is a target node!");
21050
21051   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
21052   switch (Opc) {
21053   default: break;
21054   case X86ISD::ADD:
21055   case X86ISD::SUB:
21056   case X86ISD::ADC:
21057   case X86ISD::SBB:
21058   case X86ISD::SMUL:
21059   case X86ISD::UMUL:
21060   case X86ISD::INC:
21061   case X86ISD::DEC:
21062   case X86ISD::OR:
21063   case X86ISD::XOR:
21064   case X86ISD::AND:
21065     // These nodes' second result is a boolean.
21066     if (Op.getResNo() == 0)
21067       break;
21068     // Fallthrough
21069   case X86ISD::SETCC:
21070     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21071     break;
21072   case ISD::INTRINSIC_WO_CHAIN: {
21073     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21074     unsigned NumLoBits = 0;
21075     switch (IntId) {
21076     default: break;
21077     case Intrinsic::x86_sse_movmsk_ps:
21078     case Intrinsic::x86_avx_movmsk_ps_256:
21079     case Intrinsic::x86_sse2_movmsk_pd:
21080     case Intrinsic::x86_avx_movmsk_pd_256:
21081     case Intrinsic::x86_mmx_pmovmskb:
21082     case Intrinsic::x86_sse2_pmovmskb_128:
21083     case Intrinsic::x86_avx2_pmovmskb: {
21084       // High bits of movmskp{s|d}, pmovmskb are known zero.
21085       switch (IntId) {
21086         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
21087         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
21088         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
21089         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
21090         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
21091         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
21092         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
21093         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
21094       }
21095       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21096       break;
21097     }
21098     }
21099     break;
21100   }
21101   }
21102 }
21103
21104 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21105   SDValue Op,
21106   const SelectionDAG &,
21107   unsigned Depth) const {
21108   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21109   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21110     return Op.getValueType().getScalarType().getSizeInBits();
21111
21112   // Fallback case.
21113   return 1;
21114 }
21115
21116 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21117 /// node is a GlobalAddress + offset.
21118 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21119                                        const GlobalValue* &GA,
21120                                        int64_t &Offset) const {
21121   if (N->getOpcode() == X86ISD::Wrapper) {
21122     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21123       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21124       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21125       return true;
21126     }
21127   }
21128   return TargetLowering::isGAPlusOffset(N, GA, Offset);
21129 }
21130
21131 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21132 /// same as extracting the high 128-bit part of 256-bit vector and then
21133 /// inserting the result into the low part of a new 256-bit vector
21134 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21135   EVT VT = SVOp->getValueType(0);
21136   unsigned NumElems = VT.getVectorNumElements();
21137
21138   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21139   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21140     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21141         SVOp->getMaskElt(j) >= 0)
21142       return false;
21143
21144   return true;
21145 }
21146
21147 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21148 /// same as extracting the low 128-bit part of 256-bit vector and then
21149 /// inserting the result into the high part of a new 256-bit vector
21150 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21151   EVT VT = SVOp->getValueType(0);
21152   unsigned NumElems = VT.getVectorNumElements();
21153
21154   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21155   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21156     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21157         SVOp->getMaskElt(j) >= 0)
21158       return false;
21159
21160   return true;
21161 }
21162
21163 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21164 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21165                                         TargetLowering::DAGCombinerInfo &DCI,
21166                                         const X86Subtarget* Subtarget) {
21167   SDLoc dl(N);
21168   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21169   SDValue V1 = SVOp->getOperand(0);
21170   SDValue V2 = SVOp->getOperand(1);
21171   EVT VT = SVOp->getValueType(0);
21172   unsigned NumElems = VT.getVectorNumElements();
21173
21174   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21175       V2.getOpcode() == ISD::CONCAT_VECTORS) {
21176     //
21177     //                   0,0,0,...
21178     //                      |
21179     //    V      UNDEF    BUILD_VECTOR    UNDEF
21180     //     \      /           \           /
21181     //  CONCAT_VECTOR         CONCAT_VECTOR
21182     //         \                  /
21183     //          \                /
21184     //          RESULT: V + zero extended
21185     //
21186     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21187         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21188         V1.getOperand(1).getOpcode() != ISD::UNDEF)
21189       return SDValue();
21190
21191     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21192       return SDValue();
21193
21194     // To match the shuffle mask, the first half of the mask should
21195     // be exactly the first vector, and all the rest a splat with the
21196     // first element of the second one.
21197     for (unsigned i = 0; i != NumElems/2; ++i)
21198       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21199           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21200         return SDValue();
21201
21202     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21203     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21204       if (Ld->hasNUsesOfValue(1, 0)) {
21205         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21206         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21207         SDValue ResNode =
21208           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21209                                   Ld->getMemoryVT(),
21210                                   Ld->getPointerInfo(),
21211                                   Ld->getAlignment(),
21212                                   false/*isVolatile*/, true/*ReadMem*/,
21213                                   false/*WriteMem*/);
21214
21215         // Make sure the newly-created LOAD is in the same position as Ld in
21216         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21217         // and update uses of Ld's output chain to use the TokenFactor.
21218         if (Ld->hasAnyUseOfValue(1)) {
21219           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21220                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21221           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21222           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21223                                  SDValue(ResNode.getNode(), 1));
21224         }
21225
21226         return DAG.getBitcast(VT, ResNode);
21227       }
21228     }
21229
21230     // Emit a zeroed vector and insert the desired subvector on its
21231     // first half.
21232     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21233     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21234     return DCI.CombineTo(N, InsV);
21235   }
21236
21237   //===--------------------------------------------------------------------===//
21238   // Combine some shuffles into subvector extracts and inserts:
21239   //
21240
21241   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21242   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21243     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21244     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21245     return DCI.CombineTo(N, InsV);
21246   }
21247
21248   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21249   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21250     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21251     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21252     return DCI.CombineTo(N, InsV);
21253   }
21254
21255   return SDValue();
21256 }
21257
21258 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21259 /// possible.
21260 ///
21261 /// This is the leaf of the recursive combinine below. When we have found some
21262 /// chain of single-use x86 shuffle instructions and accumulated the combined
21263 /// shuffle mask represented by them, this will try to pattern match that mask
21264 /// into either a single instruction if there is a special purpose instruction
21265 /// for this operation, or into a PSHUFB instruction which is a fully general
21266 /// instruction but should only be used to replace chains over a certain depth.
21267 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21268                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21269                                    TargetLowering::DAGCombinerInfo &DCI,
21270                                    const X86Subtarget *Subtarget) {
21271   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21272
21273   // Find the operand that enters the chain. Note that multiple uses are OK
21274   // here, we're not going to remove the operand we find.
21275   SDValue Input = Op.getOperand(0);
21276   while (Input.getOpcode() == ISD::BITCAST)
21277     Input = Input.getOperand(0);
21278
21279   MVT VT = Input.getSimpleValueType();
21280   MVT RootVT = Root.getSimpleValueType();
21281   SDLoc DL(Root);
21282
21283   // Just remove no-op shuffle masks.
21284   if (Mask.size() == 1) {
21285     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21286                   /*AddTo*/ true);
21287     return true;
21288   }
21289
21290   // Use the float domain if the operand type is a floating point type.
21291   bool FloatDomain = VT.isFloatingPoint();
21292
21293   // For floating point shuffles, we don't have free copies in the shuffle
21294   // instructions or the ability to load as part of the instruction, so
21295   // canonicalize their shuffles to UNPCK or MOV variants.
21296   //
21297   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21298   // vectors because it can have a load folded into it that UNPCK cannot. This
21299   // doesn't preclude something switching to the shorter encoding post-RA.
21300   //
21301   // FIXME: Should teach these routines about AVX vector widths.
21302   if (FloatDomain && VT.getSizeInBits() == 128) {
21303     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21304       bool Lo = Mask.equals({0, 0});
21305       unsigned Shuffle;
21306       MVT ShuffleVT;
21307       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21308       // is no slower than UNPCKLPD but has the option to fold the input operand
21309       // into even an unaligned memory load.
21310       if (Lo && Subtarget->hasSSE3()) {
21311         Shuffle = X86ISD::MOVDDUP;
21312         ShuffleVT = MVT::v2f64;
21313       } else {
21314         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21315         // than the UNPCK variants.
21316         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21317         ShuffleVT = MVT::v4f32;
21318       }
21319       if (Depth == 1 && Root->getOpcode() == Shuffle)
21320         return false; // Nothing to do!
21321       Op = DAG.getBitcast(ShuffleVT, Input);
21322       DCI.AddToWorklist(Op.getNode());
21323       if (Shuffle == X86ISD::MOVDDUP)
21324         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21325       else
21326         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21327       DCI.AddToWorklist(Op.getNode());
21328       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21329                     /*AddTo*/ true);
21330       return true;
21331     }
21332     if (Subtarget->hasSSE3() &&
21333         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21334       bool Lo = Mask.equals({0, 0, 2, 2});
21335       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21336       MVT ShuffleVT = MVT::v4f32;
21337       if (Depth == 1 && Root->getOpcode() == Shuffle)
21338         return false; // Nothing to do!
21339       Op = DAG.getBitcast(ShuffleVT, Input);
21340       DCI.AddToWorklist(Op.getNode());
21341       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21342       DCI.AddToWorklist(Op.getNode());
21343       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21344                     /*AddTo*/ true);
21345       return true;
21346     }
21347     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21348       bool Lo = Mask.equals({0, 0, 1, 1});
21349       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21350       MVT ShuffleVT = MVT::v4f32;
21351       if (Depth == 1 && Root->getOpcode() == Shuffle)
21352         return false; // Nothing to do!
21353       Op = DAG.getBitcast(ShuffleVT, Input);
21354       DCI.AddToWorklist(Op.getNode());
21355       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21356       DCI.AddToWorklist(Op.getNode());
21357       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21358                     /*AddTo*/ true);
21359       return true;
21360     }
21361   }
21362
21363   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21364   // variants as none of these have single-instruction variants that are
21365   // superior to the UNPCK formulation.
21366   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21367       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21368        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21369        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21370        Mask.equals(
21371            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21372     bool Lo = Mask[0] == 0;
21373     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21374     if (Depth == 1 && Root->getOpcode() == Shuffle)
21375       return false; // Nothing to do!
21376     MVT ShuffleVT;
21377     switch (Mask.size()) {
21378     case 8:
21379       ShuffleVT = MVT::v8i16;
21380       break;
21381     case 16:
21382       ShuffleVT = MVT::v16i8;
21383       break;
21384     default:
21385       llvm_unreachable("Impossible mask size!");
21386     };
21387     Op = DAG.getBitcast(ShuffleVT, Input);
21388     DCI.AddToWorklist(Op.getNode());
21389     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21390     DCI.AddToWorklist(Op.getNode());
21391     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21392                   /*AddTo*/ true);
21393     return true;
21394   }
21395
21396   // Don't try to re-form single instruction chains under any circumstances now
21397   // that we've done encoding canonicalization for them.
21398   if (Depth < 2)
21399     return false;
21400
21401   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21402   // can replace them with a single PSHUFB instruction profitably. Intel's
21403   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21404   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21405   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21406     SmallVector<SDValue, 16> PSHUFBMask;
21407     int NumBytes = VT.getSizeInBits() / 8;
21408     int Ratio = NumBytes / Mask.size();
21409     for (int i = 0; i < NumBytes; ++i) {
21410       if (Mask[i / Ratio] == SM_SentinelUndef) {
21411         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21412         continue;
21413       }
21414       int M = Mask[i / Ratio] != SM_SentinelZero
21415                   ? Ratio * Mask[i / Ratio] + i % Ratio
21416                   : 255;
21417       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21418     }
21419     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21420     Op = DAG.getBitcast(ByteVT, Input);
21421     DCI.AddToWorklist(Op.getNode());
21422     SDValue PSHUFBMaskOp =
21423         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21424     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21425     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21426     DCI.AddToWorklist(Op.getNode());
21427     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21428                   /*AddTo*/ true);
21429     return true;
21430   }
21431
21432   // Failed to find any combines.
21433   return false;
21434 }
21435
21436 /// \brief Fully generic combining of x86 shuffle instructions.
21437 ///
21438 /// This should be the last combine run over the x86 shuffle instructions. Once
21439 /// they have been fully optimized, this will recursively consider all chains
21440 /// of single-use shuffle instructions, build a generic model of the cumulative
21441 /// shuffle operation, and check for simpler instructions which implement this
21442 /// operation. We use this primarily for two purposes:
21443 ///
21444 /// 1) Collapse generic shuffles to specialized single instructions when
21445 ///    equivalent. In most cases, this is just an encoding size win, but
21446 ///    sometimes we will collapse multiple generic shuffles into a single
21447 ///    special-purpose shuffle.
21448 /// 2) Look for sequences of shuffle instructions with 3 or more total
21449 ///    instructions, and replace them with the slightly more expensive SSSE3
21450 ///    PSHUFB instruction if available. We do this as the last combining step
21451 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21452 ///    a suitable short sequence of other instructions. The PHUFB will either
21453 ///    use a register or have to read from memory and so is slightly (but only
21454 ///    slightly) more expensive than the other shuffle instructions.
21455 ///
21456 /// Because this is inherently a quadratic operation (for each shuffle in
21457 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21458 /// This should never be an issue in practice as the shuffle lowering doesn't
21459 /// produce sequences of more than 8 instructions.
21460 ///
21461 /// FIXME: We will currently miss some cases where the redundant shuffling
21462 /// would simplify under the threshold for PSHUFB formation because of
21463 /// combine-ordering. To fix this, we should do the redundant instruction
21464 /// combining in this recursive walk.
21465 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21466                                           ArrayRef<int> RootMask,
21467                                           int Depth, bool HasPSHUFB,
21468                                           SelectionDAG &DAG,
21469                                           TargetLowering::DAGCombinerInfo &DCI,
21470                                           const X86Subtarget *Subtarget) {
21471   // Bound the depth of our recursive combine because this is ultimately
21472   // quadratic in nature.
21473   if (Depth > 8)
21474     return false;
21475
21476   // Directly rip through bitcasts to find the underlying operand.
21477   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21478     Op = Op.getOperand(0);
21479
21480   MVT VT = Op.getSimpleValueType();
21481   if (!VT.isVector())
21482     return false; // Bail if we hit a non-vector.
21483
21484   assert(Root.getSimpleValueType().isVector() &&
21485          "Shuffles operate on vector types!");
21486   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21487          "Can only combine shuffles of the same vector register size.");
21488
21489   if (!isTargetShuffle(Op.getOpcode()))
21490     return false;
21491   SmallVector<int, 16> OpMask;
21492   bool IsUnary;
21493   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21494   // We only can combine unary shuffles which we can decode the mask for.
21495   if (!HaveMask || !IsUnary)
21496     return false;
21497
21498   assert(VT.getVectorNumElements() == OpMask.size() &&
21499          "Different mask size from vector size!");
21500   assert(((RootMask.size() > OpMask.size() &&
21501            RootMask.size() % OpMask.size() == 0) ||
21502           (OpMask.size() > RootMask.size() &&
21503            OpMask.size() % RootMask.size() == 0) ||
21504           OpMask.size() == RootMask.size()) &&
21505          "The smaller number of elements must divide the larger.");
21506   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21507   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21508   assert(((RootRatio == 1 && OpRatio == 1) ||
21509           (RootRatio == 1) != (OpRatio == 1)) &&
21510          "Must not have a ratio for both incoming and op masks!");
21511
21512   SmallVector<int, 16> Mask;
21513   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21514
21515   // Merge this shuffle operation's mask into our accumulated mask. Note that
21516   // this shuffle's mask will be the first applied to the input, followed by the
21517   // root mask to get us all the way to the root value arrangement. The reason
21518   // for this order is that we are recursing up the operation chain.
21519   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21520     int RootIdx = i / RootRatio;
21521     if (RootMask[RootIdx] < 0) {
21522       // This is a zero or undef lane, we're done.
21523       Mask.push_back(RootMask[RootIdx]);
21524       continue;
21525     }
21526
21527     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21528     int OpIdx = RootMaskedIdx / OpRatio;
21529     if (OpMask[OpIdx] < 0) {
21530       // The incoming lanes are zero or undef, it doesn't matter which ones we
21531       // are using.
21532       Mask.push_back(OpMask[OpIdx]);
21533       continue;
21534     }
21535
21536     // Ok, we have non-zero lanes, map them through.
21537     Mask.push_back(OpMask[OpIdx] * OpRatio +
21538                    RootMaskedIdx % OpRatio);
21539   }
21540
21541   // See if we can recurse into the operand to combine more things.
21542   switch (Op.getOpcode()) {
21543     case X86ISD::PSHUFB:
21544       HasPSHUFB = true;
21545     case X86ISD::PSHUFD:
21546     case X86ISD::PSHUFHW:
21547     case X86ISD::PSHUFLW:
21548       if (Op.getOperand(0).hasOneUse() &&
21549           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21550                                         HasPSHUFB, DAG, DCI, Subtarget))
21551         return true;
21552       break;
21553
21554     case X86ISD::UNPCKL:
21555     case X86ISD::UNPCKH:
21556       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21557       // We can't check for single use, we have to check that this shuffle is the only user.
21558       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21559           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21560                                         HasPSHUFB, DAG, DCI, Subtarget))
21561           return true;
21562       break;
21563   }
21564
21565   // Minor canonicalization of the accumulated shuffle mask to make it easier
21566   // to match below. All this does is detect masks with squential pairs of
21567   // elements, and shrink them to the half-width mask. It does this in a loop
21568   // so it will reduce the size of the mask to the minimal width mask which
21569   // performs an equivalent shuffle.
21570   SmallVector<int, 16> WidenedMask;
21571   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21572     Mask = std::move(WidenedMask);
21573     WidenedMask.clear();
21574   }
21575
21576   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21577                                 Subtarget);
21578 }
21579
21580 /// \brief Get the PSHUF-style mask from PSHUF node.
21581 ///
21582 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21583 /// PSHUF-style masks that can be reused with such instructions.
21584 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21585   MVT VT = N.getSimpleValueType();
21586   SmallVector<int, 4> Mask;
21587   bool IsUnary;
21588   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21589   (void)HaveMask;
21590   assert(HaveMask);
21591
21592   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21593   // matter. Check that the upper masks are repeats and remove them.
21594   if (VT.getSizeInBits() > 128) {
21595     int LaneElts = 128 / VT.getScalarSizeInBits();
21596 #ifndef NDEBUG
21597     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21598       for (int j = 0; j < LaneElts; ++j)
21599         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21600                "Mask doesn't repeat in high 128-bit lanes!");
21601 #endif
21602     Mask.resize(LaneElts);
21603   }
21604
21605   switch (N.getOpcode()) {
21606   case X86ISD::PSHUFD:
21607     return Mask;
21608   case X86ISD::PSHUFLW:
21609     Mask.resize(4);
21610     return Mask;
21611   case X86ISD::PSHUFHW:
21612     Mask.erase(Mask.begin(), Mask.begin() + 4);
21613     for (int &M : Mask)
21614       M -= 4;
21615     return Mask;
21616   default:
21617     llvm_unreachable("No valid shuffle instruction found!");
21618   }
21619 }
21620
21621 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21622 ///
21623 /// We walk up the chain and look for a combinable shuffle, skipping over
21624 /// shuffles that we could hoist this shuffle's transformation past without
21625 /// altering anything.
21626 static SDValue
21627 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21628                              SelectionDAG &DAG,
21629                              TargetLowering::DAGCombinerInfo &DCI) {
21630   assert(N.getOpcode() == X86ISD::PSHUFD &&
21631          "Called with something other than an x86 128-bit half shuffle!");
21632   SDLoc DL(N);
21633
21634   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21635   // of the shuffles in the chain so that we can form a fresh chain to replace
21636   // this one.
21637   SmallVector<SDValue, 8> Chain;
21638   SDValue V = N.getOperand(0);
21639   for (; V.hasOneUse(); V = V.getOperand(0)) {
21640     switch (V.getOpcode()) {
21641     default:
21642       return SDValue(); // Nothing combined!
21643
21644     case ISD::BITCAST:
21645       // Skip bitcasts as we always know the type for the target specific
21646       // instructions.
21647       continue;
21648
21649     case X86ISD::PSHUFD:
21650       // Found another dword shuffle.
21651       break;
21652
21653     case X86ISD::PSHUFLW:
21654       // Check that the low words (being shuffled) are the identity in the
21655       // dword shuffle, and the high words are self-contained.
21656       if (Mask[0] != 0 || Mask[1] != 1 ||
21657           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21658         return SDValue();
21659
21660       Chain.push_back(V);
21661       continue;
21662
21663     case X86ISD::PSHUFHW:
21664       // Check that the high words (being shuffled) are the identity in the
21665       // dword shuffle, and the low words are self-contained.
21666       if (Mask[2] != 2 || Mask[3] != 3 ||
21667           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21668         return SDValue();
21669
21670       Chain.push_back(V);
21671       continue;
21672
21673     case X86ISD::UNPCKL:
21674     case X86ISD::UNPCKH:
21675       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21676       // shuffle into a preceding word shuffle.
21677       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21678           V.getSimpleValueType().getScalarType() != MVT::i16)
21679         return SDValue();
21680
21681       // Search for a half-shuffle which we can combine with.
21682       unsigned CombineOp =
21683           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21684       if (V.getOperand(0) != V.getOperand(1) ||
21685           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21686         return SDValue();
21687       Chain.push_back(V);
21688       V = V.getOperand(0);
21689       do {
21690         switch (V.getOpcode()) {
21691         default:
21692           return SDValue(); // Nothing to combine.
21693
21694         case X86ISD::PSHUFLW:
21695         case X86ISD::PSHUFHW:
21696           if (V.getOpcode() == CombineOp)
21697             break;
21698
21699           Chain.push_back(V);
21700
21701           // Fallthrough!
21702         case ISD::BITCAST:
21703           V = V.getOperand(0);
21704           continue;
21705         }
21706         break;
21707       } while (V.hasOneUse());
21708       break;
21709     }
21710     // Break out of the loop if we break out of the switch.
21711     break;
21712   }
21713
21714   if (!V.hasOneUse())
21715     // We fell out of the loop without finding a viable combining instruction.
21716     return SDValue();
21717
21718   // Merge this node's mask and our incoming mask.
21719   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21720   for (int &M : Mask)
21721     M = VMask[M];
21722   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21723                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21724
21725   // Rebuild the chain around this new shuffle.
21726   while (!Chain.empty()) {
21727     SDValue W = Chain.pop_back_val();
21728
21729     if (V.getValueType() != W.getOperand(0).getValueType())
21730       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21731
21732     switch (W.getOpcode()) {
21733     default:
21734       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21735
21736     case X86ISD::UNPCKL:
21737     case X86ISD::UNPCKH:
21738       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21739       break;
21740
21741     case X86ISD::PSHUFD:
21742     case X86ISD::PSHUFLW:
21743     case X86ISD::PSHUFHW:
21744       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21745       break;
21746     }
21747   }
21748   if (V.getValueType() != N.getValueType())
21749     V = DAG.getBitcast(N.getValueType(), V);
21750
21751   // Return the new chain to replace N.
21752   return V;
21753 }
21754
21755 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21756 ///
21757 /// We walk up the chain, skipping shuffles of the other half and looking
21758 /// through shuffles which switch halves trying to find a shuffle of the same
21759 /// pair of dwords.
21760 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21761                                         SelectionDAG &DAG,
21762                                         TargetLowering::DAGCombinerInfo &DCI) {
21763   assert(
21764       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21765       "Called with something other than an x86 128-bit half shuffle!");
21766   SDLoc DL(N);
21767   unsigned CombineOpcode = N.getOpcode();
21768
21769   // Walk up a single-use chain looking for a combinable shuffle.
21770   SDValue V = N.getOperand(0);
21771   for (; V.hasOneUse(); V = V.getOperand(0)) {
21772     switch (V.getOpcode()) {
21773     default:
21774       return false; // Nothing combined!
21775
21776     case ISD::BITCAST:
21777       // Skip bitcasts as we always know the type for the target specific
21778       // instructions.
21779       continue;
21780
21781     case X86ISD::PSHUFLW:
21782     case X86ISD::PSHUFHW:
21783       if (V.getOpcode() == CombineOpcode)
21784         break;
21785
21786       // Other-half shuffles are no-ops.
21787       continue;
21788     }
21789     // Break out of the loop if we break out of the switch.
21790     break;
21791   }
21792
21793   if (!V.hasOneUse())
21794     // We fell out of the loop without finding a viable combining instruction.
21795     return false;
21796
21797   // Combine away the bottom node as its shuffle will be accumulated into
21798   // a preceding shuffle.
21799   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21800
21801   // Record the old value.
21802   SDValue Old = V;
21803
21804   // Merge this node's mask and our incoming mask (adjusted to account for all
21805   // the pshufd instructions encountered).
21806   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21807   for (int &M : Mask)
21808     M = VMask[M];
21809   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21810                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21811
21812   // Check that the shuffles didn't cancel each other out. If not, we need to
21813   // combine to the new one.
21814   if (Old != V)
21815     // Replace the combinable shuffle with the combined one, updating all users
21816     // so that we re-evaluate the chain here.
21817     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21818
21819   return true;
21820 }
21821
21822 /// \brief Try to combine x86 target specific shuffles.
21823 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21824                                            TargetLowering::DAGCombinerInfo &DCI,
21825                                            const X86Subtarget *Subtarget) {
21826   SDLoc DL(N);
21827   MVT VT = N.getSimpleValueType();
21828   SmallVector<int, 4> Mask;
21829
21830   switch (N.getOpcode()) {
21831   case X86ISD::PSHUFD:
21832   case X86ISD::PSHUFLW:
21833   case X86ISD::PSHUFHW:
21834     Mask = getPSHUFShuffleMask(N);
21835     assert(Mask.size() == 4);
21836     break;
21837   default:
21838     return SDValue();
21839   }
21840
21841   // Nuke no-op shuffles that show up after combining.
21842   if (isNoopShuffleMask(Mask))
21843     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21844
21845   // Look for simplifications involving one or two shuffle instructions.
21846   SDValue V = N.getOperand(0);
21847   switch (N.getOpcode()) {
21848   default:
21849     break;
21850   case X86ISD::PSHUFLW:
21851   case X86ISD::PSHUFHW:
21852     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21853
21854     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21855       return SDValue(); // We combined away this shuffle, so we're done.
21856
21857     // See if this reduces to a PSHUFD which is no more expensive and can
21858     // combine with more operations. Note that it has to at least flip the
21859     // dwords as otherwise it would have been removed as a no-op.
21860     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21861       int DMask[] = {0, 1, 2, 3};
21862       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21863       DMask[DOffset + 0] = DOffset + 1;
21864       DMask[DOffset + 1] = DOffset + 0;
21865       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21866       V = DAG.getBitcast(DVT, V);
21867       DCI.AddToWorklist(V.getNode());
21868       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21869                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21870       DCI.AddToWorklist(V.getNode());
21871       return DAG.getBitcast(VT, V);
21872     }
21873
21874     // Look for shuffle patterns which can be implemented as a single unpack.
21875     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21876     // only works when we have a PSHUFD followed by two half-shuffles.
21877     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21878         (V.getOpcode() == X86ISD::PSHUFLW ||
21879          V.getOpcode() == X86ISD::PSHUFHW) &&
21880         V.getOpcode() != N.getOpcode() &&
21881         V.hasOneUse()) {
21882       SDValue D = V.getOperand(0);
21883       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21884         D = D.getOperand(0);
21885       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21886         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21887         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21888         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21889         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21890         int WordMask[8];
21891         for (int i = 0; i < 4; ++i) {
21892           WordMask[i + NOffset] = Mask[i] + NOffset;
21893           WordMask[i + VOffset] = VMask[i] + VOffset;
21894         }
21895         // Map the word mask through the DWord mask.
21896         int MappedMask[8];
21897         for (int i = 0; i < 8; ++i)
21898           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21899         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21900             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21901           // We can replace all three shuffles with an unpack.
21902           V = DAG.getBitcast(VT, D.getOperand(0));
21903           DCI.AddToWorklist(V.getNode());
21904           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21905                                                 : X86ISD::UNPCKH,
21906                              DL, VT, V, V);
21907         }
21908       }
21909     }
21910
21911     break;
21912
21913   case X86ISD::PSHUFD:
21914     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21915       return NewN;
21916
21917     break;
21918   }
21919
21920   return SDValue();
21921 }
21922
21923 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21924 ///
21925 /// We combine this directly on the abstract vector shuffle nodes so it is
21926 /// easier to generically match. We also insert dummy vector shuffle nodes for
21927 /// the operands which explicitly discard the lanes which are unused by this
21928 /// operation to try to flow through the rest of the combiner the fact that
21929 /// they're unused.
21930 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21931   SDLoc DL(N);
21932   EVT VT = N->getValueType(0);
21933
21934   // We only handle target-independent shuffles.
21935   // FIXME: It would be easy and harmless to use the target shuffle mask
21936   // extraction tool to support more.
21937   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21938     return SDValue();
21939
21940   auto *SVN = cast<ShuffleVectorSDNode>(N);
21941   ArrayRef<int> Mask = SVN->getMask();
21942   SDValue V1 = N->getOperand(0);
21943   SDValue V2 = N->getOperand(1);
21944
21945   // We require the first shuffle operand to be the SUB node, and the second to
21946   // be the ADD node.
21947   // FIXME: We should support the commuted patterns.
21948   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21949     return SDValue();
21950
21951   // If there are other uses of these operations we can't fold them.
21952   if (!V1->hasOneUse() || !V2->hasOneUse())
21953     return SDValue();
21954
21955   // Ensure that both operations have the same operands. Note that we can
21956   // commute the FADD operands.
21957   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21958   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21959       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21960     return SDValue();
21961
21962   // We're looking for blends between FADD and FSUB nodes. We insist on these
21963   // nodes being lined up in a specific expected pattern.
21964   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21965         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21966         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21967     return SDValue();
21968
21969   // Only specific types are legal at this point, assert so we notice if and
21970   // when these change.
21971   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21972           VT == MVT::v4f64) &&
21973          "Unknown vector type encountered!");
21974
21975   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21976 }
21977
21978 /// PerformShuffleCombine - Performs several different shuffle combines.
21979 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21980                                      TargetLowering::DAGCombinerInfo &DCI,
21981                                      const X86Subtarget *Subtarget) {
21982   SDLoc dl(N);
21983   SDValue N0 = N->getOperand(0);
21984   SDValue N1 = N->getOperand(1);
21985   EVT VT = N->getValueType(0);
21986
21987   // Don't create instructions with illegal types after legalize types has run.
21988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21989   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21990     return SDValue();
21991
21992   // If we have legalized the vector types, look for blends of FADD and FSUB
21993   // nodes that we can fuse into an ADDSUB node.
21994   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21995     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21996       return AddSub;
21997
21998   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21999   if (Subtarget->hasFp256() && VT.is256BitVector() &&
22000       N->getOpcode() == ISD::VECTOR_SHUFFLE)
22001     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22002
22003   // During Type Legalization, when promoting illegal vector types,
22004   // the backend might introduce new shuffle dag nodes and bitcasts.
22005   //
22006   // This code performs the following transformation:
22007   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22008   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22009   //
22010   // We do this only if both the bitcast and the BINOP dag nodes have
22011   // one use. Also, perform this transformation only if the new binary
22012   // operation is legal. This is to avoid introducing dag nodes that
22013   // potentially need to be further expanded (or custom lowered) into a
22014   // less optimal sequence of dag nodes.
22015   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22016       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22017       N0.getOpcode() == ISD::BITCAST) {
22018     SDValue BC0 = N0.getOperand(0);
22019     EVT SVT = BC0.getValueType();
22020     unsigned Opcode = BC0.getOpcode();
22021     unsigned NumElts = VT.getVectorNumElements();
22022
22023     if (BC0.hasOneUse() && SVT.isVector() &&
22024         SVT.getVectorNumElements() * 2 == NumElts &&
22025         TLI.isOperationLegal(Opcode, VT)) {
22026       bool CanFold = false;
22027       switch (Opcode) {
22028       default : break;
22029       case ISD::ADD :
22030       case ISD::FADD :
22031       case ISD::SUB :
22032       case ISD::FSUB :
22033       case ISD::MUL :
22034       case ISD::FMUL :
22035         CanFold = true;
22036       }
22037
22038       unsigned SVTNumElts = SVT.getVectorNumElements();
22039       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22040       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22041         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22042       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22043         CanFold = SVOp->getMaskElt(i) < 0;
22044
22045       if (CanFold) {
22046         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22047         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22048         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22049         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22050       }
22051     }
22052   }
22053
22054   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22055   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22056   // consecutive, non-overlapping, and in the right order.
22057   SmallVector<SDValue, 16> Elts;
22058   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22059     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22060
22061   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22062     return LD;
22063
22064   if (isTargetShuffle(N->getOpcode())) {
22065     SDValue Shuffle =
22066         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22067     if (Shuffle.getNode())
22068       return Shuffle;
22069
22070     // Try recursively combining arbitrary sequences of x86 shuffle
22071     // instructions into higher-order shuffles. We do this after combining
22072     // specific PSHUF instruction sequences into their minimal form so that we
22073     // can evaluate how many specialized shuffle instructions are involved in
22074     // a particular chain.
22075     SmallVector<int, 1> NonceMask; // Just a placeholder.
22076     NonceMask.push_back(0);
22077     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22078                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22079                                       DCI, Subtarget))
22080       return SDValue(); // This routine will use CombineTo to replace N.
22081   }
22082
22083   return SDValue();
22084 }
22085
22086 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22087 /// specific shuffle of a load can be folded into a single element load.
22088 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22089 /// shuffles have been custom lowered so we need to handle those here.
22090 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22091                                          TargetLowering::DAGCombinerInfo &DCI) {
22092   if (DCI.isBeforeLegalizeOps())
22093     return SDValue();
22094
22095   SDValue InVec = N->getOperand(0);
22096   SDValue EltNo = N->getOperand(1);
22097
22098   if (!isa<ConstantSDNode>(EltNo))
22099     return SDValue();
22100
22101   EVT OriginalVT = InVec.getValueType();
22102
22103   if (InVec.getOpcode() == ISD::BITCAST) {
22104     // Don't duplicate a load with other uses.
22105     if (!InVec.hasOneUse())
22106       return SDValue();
22107     EVT BCVT = InVec.getOperand(0).getValueType();
22108     if (!BCVT.isVector() ||
22109         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22110       return SDValue();
22111     InVec = InVec.getOperand(0);
22112   }
22113
22114   EVT CurrentVT = InVec.getValueType();
22115
22116   if (!isTargetShuffle(InVec.getOpcode()))
22117     return SDValue();
22118
22119   // Don't duplicate a load with other uses.
22120   if (!InVec.hasOneUse())
22121     return SDValue();
22122
22123   SmallVector<int, 16> ShuffleMask;
22124   bool UnaryShuffle;
22125   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22126                             ShuffleMask, UnaryShuffle))
22127     return SDValue();
22128
22129   // Select the input vector, guarding against out of range extract vector.
22130   unsigned NumElems = CurrentVT.getVectorNumElements();
22131   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22132   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22133   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22134                                          : InVec.getOperand(1);
22135
22136   // If inputs to shuffle are the same for both ops, then allow 2 uses
22137   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22138                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22139
22140   if (LdNode.getOpcode() == ISD::BITCAST) {
22141     // Don't duplicate a load with other uses.
22142     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22143       return SDValue();
22144
22145     AllowedUses = 1; // only allow 1 load use if we have a bitcast
22146     LdNode = LdNode.getOperand(0);
22147   }
22148
22149   if (!ISD::isNormalLoad(LdNode.getNode()))
22150     return SDValue();
22151
22152   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22153
22154   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22155     return SDValue();
22156
22157   EVT EltVT = N->getValueType(0);
22158   // If there's a bitcast before the shuffle, check if the load type and
22159   // alignment is valid.
22160   unsigned Align = LN0->getAlignment();
22161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22162   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22163       EltVT.getTypeForEVT(*DAG.getContext()));
22164
22165   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22166     return SDValue();
22167
22168   // All checks match so transform back to vector_shuffle so that DAG combiner
22169   // can finish the job
22170   SDLoc dl(N);
22171
22172   // Create shuffle node taking into account the case that its a unary shuffle
22173   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22174                                    : InVec.getOperand(1);
22175   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22176                                  InVec.getOperand(0), Shuffle,
22177                                  &ShuffleMask[0]);
22178   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22179   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22180                      EltNo);
22181 }
22182
22183 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22184 /// special and don't usually play with other vector types, it's better to
22185 /// handle them early to be sure we emit efficient code by avoiding
22186 /// store-load conversions.
22187 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22188   if (N->getValueType(0) != MVT::x86mmx ||
22189       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22190       N->getOperand(0)->getValueType(0) != MVT::v2i32)
22191     return SDValue();
22192
22193   SDValue V = N->getOperand(0);
22194   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22195   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22196     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22197                        N->getValueType(0), V.getOperand(0));
22198
22199   return SDValue();
22200 }
22201
22202 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22203 /// generation and convert it from being a bunch of shuffles and extracts
22204 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22205 /// storing the value and loading scalars back, while for x64 we should
22206 /// use 64-bit extracts and shifts.
22207 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22208                                          TargetLowering::DAGCombinerInfo &DCI) {
22209   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22210     return NewOp;
22211
22212   SDValue InputVector = N->getOperand(0);
22213   SDLoc dl(InputVector);
22214   // Detect mmx to i32 conversion through a v2i32 elt extract.
22215   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22216       N->getValueType(0) == MVT::i32 &&
22217       InputVector.getValueType() == MVT::v2i32) {
22218
22219     // The bitcast source is a direct mmx result.
22220     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22221     if (MMXSrc.getValueType() == MVT::x86mmx)
22222       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22223                          N->getValueType(0),
22224                          InputVector.getNode()->getOperand(0));
22225
22226     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22227     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22228     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22229         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22230         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22231         MMXSrcOp.getValueType() == MVT::v1i64 &&
22232         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22233       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22234                          N->getValueType(0),
22235                          MMXSrcOp.getOperand(0));
22236   }
22237
22238   EVT VT = N->getValueType(0);
22239
22240   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22241       InputVector.getOpcode() == ISD::BITCAST &&
22242       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22243     uint64_t ExtractedElt =
22244           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22245     uint64_t InputValue =
22246           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22247     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22248     return DAG.getConstant(Res, dl, MVT::i1);
22249   }
22250   // Only operate on vectors of 4 elements, where the alternative shuffling
22251   // gets to be more expensive.
22252   if (InputVector.getValueType() != MVT::v4i32)
22253     return SDValue();
22254
22255   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22256   // single use which is a sign-extend or zero-extend, and all elements are
22257   // used.
22258   SmallVector<SDNode *, 4> Uses;
22259   unsigned ExtractedElements = 0;
22260   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22261        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22262     if (UI.getUse().getResNo() != InputVector.getResNo())
22263       return SDValue();
22264
22265     SDNode *Extract = *UI;
22266     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22267       return SDValue();
22268
22269     if (Extract->getValueType(0) != MVT::i32)
22270       return SDValue();
22271     if (!Extract->hasOneUse())
22272       return SDValue();
22273     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22274         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22275       return SDValue();
22276     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22277       return SDValue();
22278
22279     // Record which element was extracted.
22280     ExtractedElements |=
22281       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22282
22283     Uses.push_back(Extract);
22284   }
22285
22286   // If not all the elements were used, this may not be worthwhile.
22287   if (ExtractedElements != 15)
22288     return SDValue();
22289
22290   // Ok, we've now decided to do the transformation.
22291   // If 64-bit shifts are legal, use the extract-shift sequence,
22292   // otherwise bounce the vector off the cache.
22293   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22294   SDValue Vals[4];
22295
22296   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22297     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22298     auto &DL = DAG.getDataLayout();
22299     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22300     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22301       DAG.getConstant(0, dl, VecIdxTy));
22302     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22303       DAG.getConstant(1, dl, VecIdxTy));
22304
22305     SDValue ShAmt = DAG.getConstant(
22306         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22307     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22308     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22309       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22310     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22311     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22312       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22313   } else {
22314     // Store the value to a temporary stack slot.
22315     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22316     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22317       MachinePointerInfo(), false, false, 0);
22318
22319     EVT ElementType = InputVector.getValueType().getVectorElementType();
22320     unsigned EltSize = ElementType.getSizeInBits() / 8;
22321
22322     // Replace each use (extract) with a load of the appropriate element.
22323     for (unsigned i = 0; i < 4; ++i) {
22324       uint64_t Offset = EltSize * i;
22325       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22326       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22327
22328       SDValue ScalarAddr =
22329           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22330
22331       // Load the scalar.
22332       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22333                             ScalarAddr, MachinePointerInfo(),
22334                             false, false, false, 0);
22335
22336     }
22337   }
22338
22339   // Replace the extracts
22340   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22341     UE = Uses.end(); UI != UE; ++UI) {
22342     SDNode *Extract = *UI;
22343
22344     SDValue Idx = Extract->getOperand(1);
22345     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22346     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22347   }
22348
22349   // The replacement was made in place; don't return anything.
22350   return SDValue();
22351 }
22352
22353 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22354 static std::pair<unsigned, bool>
22355 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22356                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22357   if (!VT.isVector())
22358     return std::make_pair(0, false);
22359
22360   bool NeedSplit = false;
22361   switch (VT.getSimpleVT().SimpleTy) {
22362   default: return std::make_pair(0, false);
22363   case MVT::v4i64:
22364   case MVT::v2i64:
22365     if (!Subtarget->hasVLX())
22366       return std::make_pair(0, false);
22367     break;
22368   case MVT::v64i8:
22369   case MVT::v32i16:
22370     if (!Subtarget->hasBWI())
22371       return std::make_pair(0, false);
22372     break;
22373   case MVT::v16i32:
22374   case MVT::v8i64:
22375     if (!Subtarget->hasAVX512())
22376       return std::make_pair(0, false);
22377     break;
22378   case MVT::v32i8:
22379   case MVT::v16i16:
22380   case MVT::v8i32:
22381     if (!Subtarget->hasAVX2())
22382       NeedSplit = true;
22383     if (!Subtarget->hasAVX())
22384       return std::make_pair(0, false);
22385     break;
22386   case MVT::v16i8:
22387   case MVT::v8i16:
22388   case MVT::v4i32:
22389     if (!Subtarget->hasSSE2())
22390       return std::make_pair(0, false);
22391   }
22392
22393   // SSE2 has only a small subset of the operations.
22394   bool hasUnsigned = Subtarget->hasSSE41() ||
22395                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22396   bool hasSigned = Subtarget->hasSSE41() ||
22397                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22398
22399   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22400
22401   unsigned Opc = 0;
22402   // Check for x CC y ? x : y.
22403   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22404       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22405     switch (CC) {
22406     default: break;
22407     case ISD::SETULT:
22408     case ISD::SETULE:
22409       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22410     case ISD::SETUGT:
22411     case ISD::SETUGE:
22412       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22413     case ISD::SETLT:
22414     case ISD::SETLE:
22415       Opc = hasSigned ? ISD::SMIN : 0; break;
22416     case ISD::SETGT:
22417     case ISD::SETGE:
22418       Opc = hasSigned ? ISD::SMAX : 0; break;
22419     }
22420   // Check for x CC y ? y : x -- a min/max with reversed arms.
22421   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22422              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22423     switch (CC) {
22424     default: break;
22425     case ISD::SETULT:
22426     case ISD::SETULE:
22427       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22428     case ISD::SETUGT:
22429     case ISD::SETUGE:
22430       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22431     case ISD::SETLT:
22432     case ISD::SETLE:
22433       Opc = hasSigned ? ISD::SMAX : 0; break;
22434     case ISD::SETGT:
22435     case ISD::SETGE:
22436       Opc = hasSigned ? ISD::SMIN : 0; break;
22437     }
22438   }
22439
22440   return std::make_pair(Opc, NeedSplit);
22441 }
22442
22443 static SDValue
22444 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22445                                       const X86Subtarget *Subtarget) {
22446   SDLoc dl(N);
22447   SDValue Cond = N->getOperand(0);
22448   SDValue LHS = N->getOperand(1);
22449   SDValue RHS = N->getOperand(2);
22450
22451   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22452     SDValue CondSrc = Cond->getOperand(0);
22453     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22454       Cond = CondSrc->getOperand(0);
22455   }
22456
22457   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22458     return SDValue();
22459
22460   // A vselect where all conditions and data are constants can be optimized into
22461   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22462   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22463       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22464     return SDValue();
22465
22466   unsigned MaskValue = 0;
22467   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22468     return SDValue();
22469
22470   MVT VT = N->getSimpleValueType(0);
22471   unsigned NumElems = VT.getVectorNumElements();
22472   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22473   for (unsigned i = 0; i < NumElems; ++i) {
22474     // Be sure we emit undef where we can.
22475     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22476       ShuffleMask[i] = -1;
22477     else
22478       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22479   }
22480
22481   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22482   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22483     return SDValue();
22484   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22485 }
22486
22487 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22488 /// nodes.
22489 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22490                                     TargetLowering::DAGCombinerInfo &DCI,
22491                                     const X86Subtarget *Subtarget) {
22492   SDLoc DL(N);
22493   SDValue Cond = N->getOperand(0);
22494   // Get the LHS/RHS of the select.
22495   SDValue LHS = N->getOperand(1);
22496   SDValue RHS = N->getOperand(2);
22497   EVT VT = LHS.getValueType();
22498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22499
22500   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22501   // instructions match the semantics of the common C idiom x<y?x:y but not
22502   // x<=y?x:y, because of how they handle negative zero (which can be
22503   // ignored in unsafe-math mode).
22504   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22505   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22506       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22507       (Subtarget->hasSSE2() ||
22508        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22509     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22510
22511     unsigned Opcode = 0;
22512     // Check for x CC y ? x : y.
22513     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22514         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22515       switch (CC) {
22516       default: break;
22517       case ISD::SETULT:
22518         // Converting this to a min would handle NaNs incorrectly, and swapping
22519         // the operands would cause it to handle comparisons between positive
22520         // and negative zero incorrectly.
22521         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22522           if (!DAG.getTarget().Options.UnsafeFPMath &&
22523               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22524             break;
22525           std::swap(LHS, RHS);
22526         }
22527         Opcode = X86ISD::FMIN;
22528         break;
22529       case ISD::SETOLE:
22530         // Converting this to a min would handle comparisons between positive
22531         // and negative zero incorrectly.
22532         if (!DAG.getTarget().Options.UnsafeFPMath &&
22533             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22534           break;
22535         Opcode = X86ISD::FMIN;
22536         break;
22537       case ISD::SETULE:
22538         // Converting this to a min would handle both negative zeros and NaNs
22539         // incorrectly, but we can swap the operands to fix both.
22540         std::swap(LHS, RHS);
22541       case ISD::SETOLT:
22542       case ISD::SETLT:
22543       case ISD::SETLE:
22544         Opcode = X86ISD::FMIN;
22545         break;
22546
22547       case ISD::SETOGE:
22548         // Converting this to a max would handle comparisons between positive
22549         // and negative zero incorrectly.
22550         if (!DAG.getTarget().Options.UnsafeFPMath &&
22551             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22552           break;
22553         Opcode = X86ISD::FMAX;
22554         break;
22555       case ISD::SETUGT:
22556         // Converting this to a max would handle NaNs incorrectly, and swapping
22557         // the operands would cause it to handle comparisons between positive
22558         // and negative zero incorrectly.
22559         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22560           if (!DAG.getTarget().Options.UnsafeFPMath &&
22561               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22562             break;
22563           std::swap(LHS, RHS);
22564         }
22565         Opcode = X86ISD::FMAX;
22566         break;
22567       case ISD::SETUGE:
22568         // Converting this to a max would handle both negative zeros and NaNs
22569         // incorrectly, but we can swap the operands to fix both.
22570         std::swap(LHS, RHS);
22571       case ISD::SETOGT:
22572       case ISD::SETGT:
22573       case ISD::SETGE:
22574         Opcode = X86ISD::FMAX;
22575         break;
22576       }
22577     // Check for x CC y ? y : x -- a min/max with reversed arms.
22578     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22579                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22580       switch (CC) {
22581       default: break;
22582       case ISD::SETOGE:
22583         // Converting this to a min would handle comparisons between positive
22584         // and negative zero incorrectly, and swapping the operands would
22585         // cause it to handle NaNs incorrectly.
22586         if (!DAG.getTarget().Options.UnsafeFPMath &&
22587             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22588           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22589             break;
22590           std::swap(LHS, RHS);
22591         }
22592         Opcode = X86ISD::FMIN;
22593         break;
22594       case ISD::SETUGT:
22595         // Converting this to a min would handle NaNs incorrectly.
22596         if (!DAG.getTarget().Options.UnsafeFPMath &&
22597             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22598           break;
22599         Opcode = X86ISD::FMIN;
22600         break;
22601       case ISD::SETUGE:
22602         // Converting this to a min would handle both negative zeros and NaNs
22603         // incorrectly, but we can swap the operands to fix both.
22604         std::swap(LHS, RHS);
22605       case ISD::SETOGT:
22606       case ISD::SETGT:
22607       case ISD::SETGE:
22608         Opcode = X86ISD::FMIN;
22609         break;
22610
22611       case ISD::SETULT:
22612         // Converting this to a max would handle NaNs incorrectly.
22613         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22614           break;
22615         Opcode = X86ISD::FMAX;
22616         break;
22617       case ISD::SETOLE:
22618         // Converting this to a max would handle comparisons between positive
22619         // and negative zero incorrectly, and swapping the operands would
22620         // cause it to handle NaNs incorrectly.
22621         if (!DAG.getTarget().Options.UnsafeFPMath &&
22622             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22623           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22624             break;
22625           std::swap(LHS, RHS);
22626         }
22627         Opcode = X86ISD::FMAX;
22628         break;
22629       case ISD::SETULE:
22630         // Converting this to a max would handle both negative zeros and NaNs
22631         // incorrectly, but we can swap the operands to fix both.
22632         std::swap(LHS, RHS);
22633       case ISD::SETOLT:
22634       case ISD::SETLT:
22635       case ISD::SETLE:
22636         Opcode = X86ISD::FMAX;
22637         break;
22638       }
22639     }
22640
22641     if (Opcode)
22642       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22643   }
22644
22645   EVT CondVT = Cond.getValueType();
22646   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22647       CondVT.getVectorElementType() == MVT::i1) {
22648     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22649     // lowering on KNL. In this case we convert it to
22650     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22651     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22652     // Since SKX these selects have a proper lowering.
22653     EVT OpVT = LHS.getValueType();
22654     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22655         (OpVT.getVectorElementType() == MVT::i8 ||
22656          OpVT.getVectorElementType() == MVT::i16) &&
22657         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22658       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22659       DCI.AddToWorklist(Cond.getNode());
22660       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22661     }
22662   }
22663   // If this is a select between two integer constants, try to do some
22664   // optimizations.
22665   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22666     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22667       // Don't do this for crazy integer types.
22668       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22669         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22670         // so that TrueC (the true value) is larger than FalseC.
22671         bool NeedsCondInvert = false;
22672
22673         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22674             // Efficiently invertible.
22675             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22676              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22677               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22678           NeedsCondInvert = true;
22679           std::swap(TrueC, FalseC);
22680         }
22681
22682         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22683         if (FalseC->getAPIntValue() == 0 &&
22684             TrueC->getAPIntValue().isPowerOf2()) {
22685           if (NeedsCondInvert) // Invert the condition if needed.
22686             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22687                                DAG.getConstant(1, DL, Cond.getValueType()));
22688
22689           // Zero extend the condition if needed.
22690           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22691
22692           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22693           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22694                              DAG.getConstant(ShAmt, DL, MVT::i8));
22695         }
22696
22697         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22698         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22699           if (NeedsCondInvert) // Invert the condition if needed.
22700             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22701                                DAG.getConstant(1, DL, Cond.getValueType()));
22702
22703           // Zero extend the condition if needed.
22704           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22705                              FalseC->getValueType(0), Cond);
22706           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22707                              SDValue(FalseC, 0));
22708         }
22709
22710         // Optimize cases that will turn into an LEA instruction.  This requires
22711         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22712         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22713           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22714           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22715
22716           bool isFastMultiplier = false;
22717           if (Diff < 10) {
22718             switch ((unsigned char)Diff) {
22719               default: break;
22720               case 1:  // result = add base, cond
22721               case 2:  // result = lea base(    , cond*2)
22722               case 3:  // result = lea base(cond, cond*2)
22723               case 4:  // result = lea base(    , cond*4)
22724               case 5:  // result = lea base(cond, cond*4)
22725               case 8:  // result = lea base(    , cond*8)
22726               case 9:  // result = lea base(cond, cond*8)
22727                 isFastMultiplier = true;
22728                 break;
22729             }
22730           }
22731
22732           if (isFastMultiplier) {
22733             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22734             if (NeedsCondInvert) // Invert the condition if needed.
22735               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22736                                  DAG.getConstant(1, DL, Cond.getValueType()));
22737
22738             // Zero extend the condition if needed.
22739             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22740                                Cond);
22741             // Scale the condition by the difference.
22742             if (Diff != 1)
22743               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22744                                  DAG.getConstant(Diff, DL,
22745                                                  Cond.getValueType()));
22746
22747             // Add the base if non-zero.
22748             if (FalseC->getAPIntValue() != 0)
22749               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22750                                  SDValue(FalseC, 0));
22751             return Cond;
22752           }
22753         }
22754       }
22755   }
22756
22757   // Canonicalize max and min:
22758   // (x > y) ? x : y -> (x >= y) ? x : y
22759   // (x < y) ? x : y -> (x <= y) ? x : y
22760   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22761   // the need for an extra compare
22762   // against zero. e.g.
22763   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22764   // subl   %esi, %edi
22765   // testl  %edi, %edi
22766   // movl   $0, %eax
22767   // cmovgl %edi, %eax
22768   // =>
22769   // xorl   %eax, %eax
22770   // subl   %esi, $edi
22771   // cmovsl %eax, %edi
22772   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22773       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22774       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22775     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22776     switch (CC) {
22777     default: break;
22778     case ISD::SETLT:
22779     case ISD::SETGT: {
22780       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22781       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22782                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22783       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22784     }
22785     }
22786   }
22787
22788   // Early exit check
22789   if (!TLI.isTypeLegal(VT))
22790     return SDValue();
22791
22792   // Match VSELECTs into subs with unsigned saturation.
22793   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22794       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22795       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22796        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22797     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22798
22799     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22800     // left side invert the predicate to simplify logic below.
22801     SDValue Other;
22802     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22803       Other = RHS;
22804       CC = ISD::getSetCCInverse(CC, true);
22805     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22806       Other = LHS;
22807     }
22808
22809     if (Other.getNode() && Other->getNumOperands() == 2 &&
22810         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22811       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22812       SDValue CondRHS = Cond->getOperand(1);
22813
22814       // Look for a general sub with unsigned saturation first.
22815       // x >= y ? x-y : 0 --> subus x, y
22816       // x >  y ? x-y : 0 --> subus x, y
22817       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22818           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22819         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22820
22821       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22822         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22823           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22824             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22825               // If the RHS is a constant we have to reverse the const
22826               // canonicalization.
22827               // x > C-1 ? x+-C : 0 --> subus x, C
22828               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22829                   CondRHSConst->getAPIntValue() ==
22830                       (-OpRHSConst->getAPIntValue() - 1))
22831                 return DAG.getNode(
22832                     X86ISD::SUBUS, DL, VT, OpLHS,
22833                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22834
22835           // Another special case: If C was a sign bit, the sub has been
22836           // canonicalized into a xor.
22837           // FIXME: Would it be better to use computeKnownBits to determine
22838           //        whether it's safe to decanonicalize the xor?
22839           // x s< 0 ? x^C : 0 --> subus x, C
22840           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22841               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22842               OpRHSConst->getAPIntValue().isSignBit())
22843             // Note that we have to rebuild the RHS constant here to ensure we
22844             // don't rely on particular values of undef lanes.
22845             return DAG.getNode(
22846                 X86ISD::SUBUS, DL, VT, OpLHS,
22847                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22848         }
22849     }
22850   }
22851
22852   // Try to match a min/max vector operation.
22853   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22854     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22855     unsigned Opc = ret.first;
22856     bool NeedSplit = ret.second;
22857
22858     if (Opc && NeedSplit) {
22859       unsigned NumElems = VT.getVectorNumElements();
22860       // Extract the LHS vectors
22861       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22862       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22863
22864       // Extract the RHS vectors
22865       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22866       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22867
22868       // Create min/max for each subvector
22869       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22870       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22871
22872       // Merge the result
22873       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22874     } else if (Opc)
22875       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22876   }
22877
22878   // Simplify vector selection if condition value type matches vselect
22879   // operand type
22880   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22881     assert(Cond.getValueType().isVector() &&
22882            "vector select expects a vector selector!");
22883
22884     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22885     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22886
22887     // Try invert the condition if true value is not all 1s and false value
22888     // is not all 0s.
22889     if (!TValIsAllOnes && !FValIsAllZeros &&
22890         // Check if the selector will be produced by CMPP*/PCMP*
22891         Cond.getOpcode() == ISD::SETCC &&
22892         // Check if SETCC has already been promoted
22893         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22894             CondVT) {
22895       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22896       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22897
22898       if (TValIsAllZeros || FValIsAllOnes) {
22899         SDValue CC = Cond.getOperand(2);
22900         ISD::CondCode NewCC =
22901           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22902                                Cond.getOperand(0).getValueType().isInteger());
22903         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22904         std::swap(LHS, RHS);
22905         TValIsAllOnes = FValIsAllOnes;
22906         FValIsAllZeros = TValIsAllZeros;
22907       }
22908     }
22909
22910     if (TValIsAllOnes || FValIsAllZeros) {
22911       SDValue Ret;
22912
22913       if (TValIsAllOnes && FValIsAllZeros)
22914         Ret = Cond;
22915       else if (TValIsAllOnes)
22916         Ret =
22917             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22918       else if (FValIsAllZeros)
22919         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22920                           DAG.getBitcast(CondVT, LHS));
22921
22922       return DAG.getBitcast(VT, Ret);
22923     }
22924   }
22925
22926   // We should generate an X86ISD::BLENDI from a vselect if its argument
22927   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22928   // constants. This specific pattern gets generated when we split a
22929   // selector for a 512 bit vector in a machine without AVX512 (but with
22930   // 256-bit vectors), during legalization:
22931   //
22932   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22933   //
22934   // Iff we find this pattern and the build_vectors are built from
22935   // constants, we translate the vselect into a shuffle_vector that we
22936   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22937   if ((N->getOpcode() == ISD::VSELECT ||
22938        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22939       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22940     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22941     if (Shuffle.getNode())
22942       return Shuffle;
22943   }
22944
22945   // If this is a *dynamic* select (non-constant condition) and we can match
22946   // this node with one of the variable blend instructions, restructure the
22947   // condition so that the blends can use the high bit of each element and use
22948   // SimplifyDemandedBits to simplify the condition operand.
22949   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22950       !DCI.isBeforeLegalize() &&
22951       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22952     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22953
22954     // Don't optimize vector selects that map to mask-registers.
22955     if (BitWidth == 1)
22956       return SDValue();
22957
22958     // We can only handle the cases where VSELECT is directly legal on the
22959     // subtarget. We custom lower VSELECT nodes with constant conditions and
22960     // this makes it hard to see whether a dynamic VSELECT will correctly
22961     // lower, so we both check the operation's status and explicitly handle the
22962     // cases where a *dynamic* blend will fail even though a constant-condition
22963     // blend could be custom lowered.
22964     // FIXME: We should find a better way to handle this class of problems.
22965     // Potentially, we should combine constant-condition vselect nodes
22966     // pre-legalization into shuffles and not mark as many types as custom
22967     // lowered.
22968     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22969       return SDValue();
22970     // FIXME: We don't support i16-element blends currently. We could and
22971     // should support them by making *all* the bits in the condition be set
22972     // rather than just the high bit and using an i8-element blend.
22973     if (VT.getScalarType() == MVT::i16)
22974       return SDValue();
22975     // Dynamic blending was only available from SSE4.1 onward.
22976     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22977       return SDValue();
22978     // Byte blends are only available in AVX2
22979     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22980         !Subtarget->hasAVX2())
22981       return SDValue();
22982
22983     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22984     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22985
22986     APInt KnownZero, KnownOne;
22987     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22988                                           DCI.isBeforeLegalizeOps());
22989     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22990         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22991                                  TLO)) {
22992       // If we changed the computation somewhere in the DAG, this change
22993       // will affect all users of Cond.
22994       // Make sure it is fine and update all the nodes so that we do not
22995       // use the generic VSELECT anymore. Otherwise, we may perform
22996       // wrong optimizations as we messed up with the actual expectation
22997       // for the vector boolean values.
22998       if (Cond != TLO.Old) {
22999         // Check all uses of that condition operand to check whether it will be
23000         // consumed by non-BLEND instructions, which may depend on all bits are
23001         // set properly.
23002         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23003              I != E; ++I)
23004           if (I->getOpcode() != ISD::VSELECT)
23005             // TODO: Add other opcodes eventually lowered into BLEND.
23006             return SDValue();
23007
23008         // Update all the users of the condition, before committing the change,
23009         // so that the VSELECT optimizations that expect the correct vector
23010         // boolean value will not be triggered.
23011         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23012              I != E; ++I)
23013           DAG.ReplaceAllUsesOfValueWith(
23014               SDValue(*I, 0),
23015               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23016                           Cond, I->getOperand(1), I->getOperand(2)));
23017         DCI.CommitTargetLoweringOpt(TLO);
23018         return SDValue();
23019       }
23020       // At this point, only Cond is changed. Change the condition
23021       // just for N to keep the opportunity to optimize all other
23022       // users their own way.
23023       DAG.ReplaceAllUsesOfValueWith(
23024           SDValue(N, 0),
23025           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23026                       TLO.New, N->getOperand(1), N->getOperand(2)));
23027       return SDValue();
23028     }
23029   }
23030
23031   return SDValue();
23032 }
23033
23034 // Check whether a boolean test is testing a boolean value generated by
23035 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23036 // code.
23037 //
23038 // Simplify the following patterns:
23039 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23040 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23041 // to (Op EFLAGS Cond)
23042 //
23043 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23044 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23045 // to (Op EFLAGS !Cond)
23046 //
23047 // where Op could be BRCOND or CMOV.
23048 //
23049 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23050   // Quit if not CMP and SUB with its value result used.
23051   if (Cmp.getOpcode() != X86ISD::CMP &&
23052       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23053       return SDValue();
23054
23055   // Quit if not used as a boolean value.
23056   if (CC != X86::COND_E && CC != X86::COND_NE)
23057     return SDValue();
23058
23059   // Check CMP operands. One of them should be 0 or 1 and the other should be
23060   // an SetCC or extended from it.
23061   SDValue Op1 = Cmp.getOperand(0);
23062   SDValue Op2 = Cmp.getOperand(1);
23063
23064   SDValue SetCC;
23065   const ConstantSDNode* C = nullptr;
23066   bool needOppositeCond = (CC == X86::COND_E);
23067   bool checkAgainstTrue = false; // Is it a comparison against 1?
23068
23069   if ((C = dyn_cast<ConstantSDNode>(Op1)))
23070     SetCC = Op2;
23071   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23072     SetCC = Op1;
23073   else // Quit if all operands are not constants.
23074     return SDValue();
23075
23076   if (C->getZExtValue() == 1) {
23077     needOppositeCond = !needOppositeCond;
23078     checkAgainstTrue = true;
23079   } else if (C->getZExtValue() != 0)
23080     // Quit if the constant is neither 0 or 1.
23081     return SDValue();
23082
23083   bool truncatedToBoolWithAnd = false;
23084   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23085   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23086          SetCC.getOpcode() == ISD::TRUNCATE ||
23087          SetCC.getOpcode() == ISD::AND) {
23088     if (SetCC.getOpcode() == ISD::AND) {
23089       int OpIdx = -1;
23090       ConstantSDNode *CS;
23091       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23092           CS->getZExtValue() == 1)
23093         OpIdx = 1;
23094       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23095           CS->getZExtValue() == 1)
23096         OpIdx = 0;
23097       if (OpIdx == -1)
23098         break;
23099       SetCC = SetCC.getOperand(OpIdx);
23100       truncatedToBoolWithAnd = true;
23101     } else
23102       SetCC = SetCC.getOperand(0);
23103   }
23104
23105   switch (SetCC.getOpcode()) {
23106   case X86ISD::SETCC_CARRY:
23107     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23108     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23109     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23110     // truncated to i1 using 'and'.
23111     if (checkAgainstTrue && !truncatedToBoolWithAnd)
23112       break;
23113     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23114            "Invalid use of SETCC_CARRY!");
23115     // FALL THROUGH
23116   case X86ISD::SETCC:
23117     // Set the condition code or opposite one if necessary.
23118     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23119     if (needOppositeCond)
23120       CC = X86::GetOppositeBranchCondition(CC);
23121     return SetCC.getOperand(1);
23122   case X86ISD::CMOV: {
23123     // Check whether false/true value has canonical one, i.e. 0 or 1.
23124     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23125     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23126     // Quit if true value is not a constant.
23127     if (!TVal)
23128       return SDValue();
23129     // Quit if false value is not a constant.
23130     if (!FVal) {
23131       SDValue Op = SetCC.getOperand(0);
23132       // Skip 'zext' or 'trunc' node.
23133       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23134           Op.getOpcode() == ISD::TRUNCATE)
23135         Op = Op.getOperand(0);
23136       // A special case for rdrand/rdseed, where 0 is set if false cond is
23137       // found.
23138       if ((Op.getOpcode() != X86ISD::RDRAND &&
23139            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23140         return SDValue();
23141     }
23142     // Quit if false value is not the constant 0 or 1.
23143     bool FValIsFalse = true;
23144     if (FVal && FVal->getZExtValue() != 0) {
23145       if (FVal->getZExtValue() != 1)
23146         return SDValue();
23147       // If FVal is 1, opposite cond is needed.
23148       needOppositeCond = !needOppositeCond;
23149       FValIsFalse = false;
23150     }
23151     // Quit if TVal is not the constant opposite of FVal.
23152     if (FValIsFalse && TVal->getZExtValue() != 1)
23153       return SDValue();
23154     if (!FValIsFalse && TVal->getZExtValue() != 0)
23155       return SDValue();
23156     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23157     if (needOppositeCond)
23158       CC = X86::GetOppositeBranchCondition(CC);
23159     return SetCC.getOperand(3);
23160   }
23161   }
23162
23163   return SDValue();
23164 }
23165
23166 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23167 /// Match:
23168 ///   (X86or (X86setcc) (X86setcc))
23169 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
23170 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23171                                            X86::CondCode &CC1, SDValue &Flags,
23172                                            bool &isAnd) {
23173   if (Cond->getOpcode() == X86ISD::CMP) {
23174     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23175     if (!CondOp1C || !CondOp1C->isNullValue())
23176       return false;
23177
23178     Cond = Cond->getOperand(0);
23179   }
23180
23181   isAnd = false;
23182
23183   SDValue SetCC0, SetCC1;
23184   switch (Cond->getOpcode()) {
23185   default: return false;
23186   case ISD::AND:
23187   case X86ISD::AND:
23188     isAnd = true;
23189     // fallthru
23190   case ISD::OR:
23191   case X86ISD::OR:
23192     SetCC0 = Cond->getOperand(0);
23193     SetCC1 = Cond->getOperand(1);
23194     break;
23195   };
23196
23197   // Make sure we have SETCC nodes, using the same flags value.
23198   if (SetCC0.getOpcode() != X86ISD::SETCC ||
23199       SetCC1.getOpcode() != X86ISD::SETCC ||
23200       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23201     return false;
23202
23203   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23204   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23205   Flags = SetCC0->getOperand(1);
23206   return true;
23207 }
23208
23209 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23210 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23211                                   TargetLowering::DAGCombinerInfo &DCI,
23212                                   const X86Subtarget *Subtarget) {
23213   SDLoc DL(N);
23214
23215   // If the flag operand isn't dead, don't touch this CMOV.
23216   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23217     return SDValue();
23218
23219   SDValue FalseOp = N->getOperand(0);
23220   SDValue TrueOp = N->getOperand(1);
23221   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23222   SDValue Cond = N->getOperand(3);
23223
23224   if (CC == X86::COND_E || CC == X86::COND_NE) {
23225     switch (Cond.getOpcode()) {
23226     default: break;
23227     case X86ISD::BSR:
23228     case X86ISD::BSF:
23229       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23230       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23231         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23232     }
23233   }
23234
23235   SDValue Flags;
23236
23237   Flags = checkBoolTestSetCCCombine(Cond, CC);
23238   if (Flags.getNode() &&
23239       // Extra check as FCMOV only supports a subset of X86 cond.
23240       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23241     SDValue Ops[] = { FalseOp, TrueOp,
23242                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23243     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23244   }
23245
23246   // If this is a select between two integer constants, try to do some
23247   // optimizations.  Note that the operands are ordered the opposite of SELECT
23248   // operands.
23249   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23250     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23251       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23252       // larger than FalseC (the false value).
23253       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23254         CC = X86::GetOppositeBranchCondition(CC);
23255         std::swap(TrueC, FalseC);
23256         std::swap(TrueOp, FalseOp);
23257       }
23258
23259       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23260       // This is efficient for any integer data type (including i8/i16) and
23261       // shift amount.
23262       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23263         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23264                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23265
23266         // Zero extend the condition if needed.
23267         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23268
23269         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23270         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23271                            DAG.getConstant(ShAmt, DL, MVT::i8));
23272         if (N->getNumValues() == 2)  // Dead flag value?
23273           return DCI.CombineTo(N, Cond, SDValue());
23274         return Cond;
23275       }
23276
23277       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23278       // for any integer data type, including i8/i16.
23279       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23280         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23281                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23282
23283         // Zero extend the condition if needed.
23284         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23285                            FalseC->getValueType(0), Cond);
23286         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23287                            SDValue(FalseC, 0));
23288
23289         if (N->getNumValues() == 2)  // Dead flag value?
23290           return DCI.CombineTo(N, Cond, SDValue());
23291         return Cond;
23292       }
23293
23294       // Optimize cases that will turn into an LEA instruction.  This requires
23295       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23296       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23297         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23298         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23299
23300         bool isFastMultiplier = false;
23301         if (Diff < 10) {
23302           switch ((unsigned char)Diff) {
23303           default: break;
23304           case 1:  // result = add base, cond
23305           case 2:  // result = lea base(    , cond*2)
23306           case 3:  // result = lea base(cond, cond*2)
23307           case 4:  // result = lea base(    , cond*4)
23308           case 5:  // result = lea base(cond, cond*4)
23309           case 8:  // result = lea base(    , cond*8)
23310           case 9:  // result = lea base(cond, cond*8)
23311             isFastMultiplier = true;
23312             break;
23313           }
23314         }
23315
23316         if (isFastMultiplier) {
23317           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23318           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23319                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23320           // Zero extend the condition if needed.
23321           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23322                              Cond);
23323           // Scale the condition by the difference.
23324           if (Diff != 1)
23325             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23326                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23327
23328           // Add the base if non-zero.
23329           if (FalseC->getAPIntValue() != 0)
23330             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23331                                SDValue(FalseC, 0));
23332           if (N->getNumValues() == 2)  // Dead flag value?
23333             return DCI.CombineTo(N, Cond, SDValue());
23334           return Cond;
23335         }
23336       }
23337     }
23338   }
23339
23340   // Handle these cases:
23341   //   (select (x != c), e, c) -> select (x != c), e, x),
23342   //   (select (x == c), c, e) -> select (x == c), x, e)
23343   // where the c is an integer constant, and the "select" is the combination
23344   // of CMOV and CMP.
23345   //
23346   // The rationale for this change is that the conditional-move from a constant
23347   // needs two instructions, however, conditional-move from a register needs
23348   // only one instruction.
23349   //
23350   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23351   //  some instruction-combining opportunities. This opt needs to be
23352   //  postponed as late as possible.
23353   //
23354   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23355     // the DCI.xxxx conditions are provided to postpone the optimization as
23356     // late as possible.
23357
23358     ConstantSDNode *CmpAgainst = nullptr;
23359     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23360         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23361         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23362
23363       if (CC == X86::COND_NE &&
23364           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23365         CC = X86::GetOppositeBranchCondition(CC);
23366         std::swap(TrueOp, FalseOp);
23367       }
23368
23369       if (CC == X86::COND_E &&
23370           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23371         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23372                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23373         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23374       }
23375     }
23376   }
23377
23378   // Fold and/or of setcc's to double CMOV:
23379   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23380   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23381   //
23382   // This combine lets us generate:
23383   //   cmovcc1 (jcc1 if we don't have CMOV)
23384   //   cmovcc2 (same)
23385   // instead of:
23386   //   setcc1
23387   //   setcc2
23388   //   and/or
23389   //   cmovne (jne if we don't have CMOV)
23390   // When we can't use the CMOV instruction, it might increase branch
23391   // mispredicts.
23392   // When we can use CMOV, or when there is no mispredict, this improves
23393   // throughput and reduces register pressure.
23394   //
23395   if (CC == X86::COND_NE) {
23396     SDValue Flags;
23397     X86::CondCode CC0, CC1;
23398     bool isAndSetCC;
23399     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23400       if (isAndSetCC) {
23401         std::swap(FalseOp, TrueOp);
23402         CC0 = X86::GetOppositeBranchCondition(CC0);
23403         CC1 = X86::GetOppositeBranchCondition(CC1);
23404       }
23405
23406       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23407         Flags};
23408       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23409       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23410       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23411       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23412       return CMOV;
23413     }
23414   }
23415
23416   return SDValue();
23417 }
23418
23419 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23420                                                 const X86Subtarget *Subtarget) {
23421   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23422   switch (IntNo) {
23423   default: return SDValue();
23424   // SSE/AVX/AVX2 blend intrinsics.
23425   case Intrinsic::x86_avx2_pblendvb:
23426     // Don't try to simplify this intrinsic if we don't have AVX2.
23427     if (!Subtarget->hasAVX2())
23428       return SDValue();
23429     // FALL-THROUGH
23430   case Intrinsic::x86_avx_blendv_pd_256:
23431   case Intrinsic::x86_avx_blendv_ps_256:
23432     // Don't try to simplify this intrinsic if we don't have AVX.
23433     if (!Subtarget->hasAVX())
23434       return SDValue();
23435     // FALL-THROUGH
23436   case Intrinsic::x86_sse41_blendvps:
23437   case Intrinsic::x86_sse41_blendvpd:
23438   case Intrinsic::x86_sse41_pblendvb: {
23439     SDValue Op0 = N->getOperand(1);
23440     SDValue Op1 = N->getOperand(2);
23441     SDValue Mask = N->getOperand(3);
23442
23443     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23444     if (!Subtarget->hasSSE41())
23445       return SDValue();
23446
23447     // fold (blend A, A, Mask) -> A
23448     if (Op0 == Op1)
23449       return Op0;
23450     // fold (blend A, B, allZeros) -> A
23451     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23452       return Op0;
23453     // fold (blend A, B, allOnes) -> B
23454     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23455       return Op1;
23456
23457     // Simplify the case where the mask is a constant i32 value.
23458     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23459       if (C->isNullValue())
23460         return Op0;
23461       if (C->isAllOnesValue())
23462         return Op1;
23463     }
23464
23465     return SDValue();
23466   }
23467
23468   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23469   case Intrinsic::x86_sse2_psrai_w:
23470   case Intrinsic::x86_sse2_psrai_d:
23471   case Intrinsic::x86_avx2_psrai_w:
23472   case Intrinsic::x86_avx2_psrai_d:
23473   case Intrinsic::x86_sse2_psra_w:
23474   case Intrinsic::x86_sse2_psra_d:
23475   case Intrinsic::x86_avx2_psra_w:
23476   case Intrinsic::x86_avx2_psra_d: {
23477     SDValue Op0 = N->getOperand(1);
23478     SDValue Op1 = N->getOperand(2);
23479     EVT VT = Op0.getValueType();
23480     assert(VT.isVector() && "Expected a vector type!");
23481
23482     if (isa<BuildVectorSDNode>(Op1))
23483       Op1 = Op1.getOperand(0);
23484
23485     if (!isa<ConstantSDNode>(Op1))
23486       return SDValue();
23487
23488     EVT SVT = VT.getVectorElementType();
23489     unsigned SVTBits = SVT.getSizeInBits();
23490
23491     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23492     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23493     uint64_t ShAmt = C.getZExtValue();
23494
23495     // Don't try to convert this shift into a ISD::SRA if the shift
23496     // count is bigger than or equal to the element size.
23497     if (ShAmt >= SVTBits)
23498       return SDValue();
23499
23500     // Trivial case: if the shift count is zero, then fold this
23501     // into the first operand.
23502     if (ShAmt == 0)
23503       return Op0;
23504
23505     // Replace this packed shift intrinsic with a target independent
23506     // shift dag node.
23507     SDLoc DL(N);
23508     SDValue Splat = DAG.getConstant(C, DL, VT);
23509     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23510   }
23511   }
23512 }
23513
23514 /// PerformMulCombine - Optimize a single multiply with constant into two
23515 /// in order to implement it with two cheaper instructions, e.g.
23516 /// LEA + SHL, LEA + LEA.
23517 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23518                                  TargetLowering::DAGCombinerInfo &DCI) {
23519   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23520     return SDValue();
23521
23522   EVT VT = N->getValueType(0);
23523   if (VT != MVT::i64 && VT != MVT::i32)
23524     return SDValue();
23525
23526   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23527   if (!C)
23528     return SDValue();
23529   uint64_t MulAmt = C->getZExtValue();
23530   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23531     return SDValue();
23532
23533   uint64_t MulAmt1 = 0;
23534   uint64_t MulAmt2 = 0;
23535   if ((MulAmt % 9) == 0) {
23536     MulAmt1 = 9;
23537     MulAmt2 = MulAmt / 9;
23538   } else if ((MulAmt % 5) == 0) {
23539     MulAmt1 = 5;
23540     MulAmt2 = MulAmt / 5;
23541   } else if ((MulAmt % 3) == 0) {
23542     MulAmt1 = 3;
23543     MulAmt2 = MulAmt / 3;
23544   }
23545   if (MulAmt2 &&
23546       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23547     SDLoc DL(N);
23548
23549     if (isPowerOf2_64(MulAmt2) &&
23550         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23551       // If second multiplifer is pow2, issue it first. We want the multiply by
23552       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23553       // is an add.
23554       std::swap(MulAmt1, MulAmt2);
23555
23556     SDValue NewMul;
23557     if (isPowerOf2_64(MulAmt1))
23558       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23559                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23560     else
23561       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23562                            DAG.getConstant(MulAmt1, DL, VT));
23563
23564     if (isPowerOf2_64(MulAmt2))
23565       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23566                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23567     else
23568       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23569                            DAG.getConstant(MulAmt2, DL, VT));
23570
23571     // Do not add new nodes to DAG combiner worklist.
23572     DCI.CombineTo(N, NewMul, false);
23573   }
23574   return SDValue();
23575 }
23576
23577 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23578   SDValue N0 = N->getOperand(0);
23579   SDValue N1 = N->getOperand(1);
23580   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23581   EVT VT = N0.getValueType();
23582
23583   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23584   // since the result of setcc_c is all zero's or all ones.
23585   if (VT.isInteger() && !VT.isVector() &&
23586       N1C && N0.getOpcode() == ISD::AND &&
23587       N0.getOperand(1).getOpcode() == ISD::Constant) {
23588     SDValue N00 = N0.getOperand(0);
23589     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23590         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23591           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23592          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23593       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23594       APInt ShAmt = N1C->getAPIntValue();
23595       Mask = Mask.shl(ShAmt);
23596       if (Mask != 0) {
23597         SDLoc DL(N);
23598         return DAG.getNode(ISD::AND, DL, VT,
23599                            N00, DAG.getConstant(Mask, DL, VT));
23600       }
23601     }
23602   }
23603
23604   // Hardware support for vector shifts is sparse which makes us scalarize the
23605   // vector operations in many cases. Also, on sandybridge ADD is faster than
23606   // shl.
23607   // (shl V, 1) -> add V,V
23608   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23609     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23610       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23611       // We shift all of the values by one. In many cases we do not have
23612       // hardware support for this operation. This is better expressed as an ADD
23613       // of two values.
23614       if (N1SplatC->getAPIntValue() == 1)
23615         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23616     }
23617
23618   return SDValue();
23619 }
23620
23621 /// \brief Returns a vector of 0s if the node in input is a vector logical
23622 /// shift by a constant amount which is known to be bigger than or equal
23623 /// to the vector element size in bits.
23624 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23625                                       const X86Subtarget *Subtarget) {
23626   EVT VT = N->getValueType(0);
23627
23628   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23629       (!Subtarget->hasInt256() ||
23630        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23631     return SDValue();
23632
23633   SDValue Amt = N->getOperand(1);
23634   SDLoc DL(N);
23635   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23636     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23637       APInt ShiftAmt = AmtSplat->getAPIntValue();
23638       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23639
23640       // SSE2/AVX2 logical shifts always return a vector of 0s
23641       // if the shift amount is bigger than or equal to
23642       // the element size. The constant shift amount will be
23643       // encoded as a 8-bit immediate.
23644       if (ShiftAmt.trunc(8).uge(MaxAmount))
23645         return getZeroVector(VT, Subtarget, DAG, DL);
23646     }
23647
23648   return SDValue();
23649 }
23650
23651 /// PerformShiftCombine - Combine shifts.
23652 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23653                                    TargetLowering::DAGCombinerInfo &DCI,
23654                                    const X86Subtarget *Subtarget) {
23655   if (N->getOpcode() == ISD::SHL)
23656     if (SDValue V = PerformSHLCombine(N, DAG))
23657       return V;
23658
23659   // Try to fold this logical shift into a zero vector.
23660   if (N->getOpcode() != ISD::SRA)
23661     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23662       return V;
23663
23664   return SDValue();
23665 }
23666
23667 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23668 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23669 // and friends.  Likewise for OR -> CMPNEQSS.
23670 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23671                             TargetLowering::DAGCombinerInfo &DCI,
23672                             const X86Subtarget *Subtarget) {
23673   unsigned opcode;
23674
23675   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23676   // we're requiring SSE2 for both.
23677   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23678     SDValue N0 = N->getOperand(0);
23679     SDValue N1 = N->getOperand(1);
23680     SDValue CMP0 = N0->getOperand(1);
23681     SDValue CMP1 = N1->getOperand(1);
23682     SDLoc DL(N);
23683
23684     // The SETCCs should both refer to the same CMP.
23685     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23686       return SDValue();
23687
23688     SDValue CMP00 = CMP0->getOperand(0);
23689     SDValue CMP01 = CMP0->getOperand(1);
23690     EVT     VT    = CMP00.getValueType();
23691
23692     if (VT == MVT::f32 || VT == MVT::f64) {
23693       bool ExpectingFlags = false;
23694       // Check for any users that want flags:
23695       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23696            !ExpectingFlags && UI != UE; ++UI)
23697         switch (UI->getOpcode()) {
23698         default:
23699         case ISD::BR_CC:
23700         case ISD::BRCOND:
23701         case ISD::SELECT:
23702           ExpectingFlags = true;
23703           break;
23704         case ISD::CopyToReg:
23705         case ISD::SIGN_EXTEND:
23706         case ISD::ZERO_EXTEND:
23707         case ISD::ANY_EXTEND:
23708           break;
23709         }
23710
23711       if (!ExpectingFlags) {
23712         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23713         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23714
23715         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23716           X86::CondCode tmp = cc0;
23717           cc0 = cc1;
23718           cc1 = tmp;
23719         }
23720
23721         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23722             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23723           // FIXME: need symbolic constants for these magic numbers.
23724           // See X86ATTInstPrinter.cpp:printSSECC().
23725           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23726           if (Subtarget->hasAVX512()) {
23727             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23728                                          CMP01,
23729                                          DAG.getConstant(x86cc, DL, MVT::i8));
23730             if (N->getValueType(0) != MVT::i1)
23731               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23732                                  FSetCC);
23733             return FSetCC;
23734           }
23735           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23736                                               CMP00.getValueType(), CMP00, CMP01,
23737                                               DAG.getConstant(x86cc, DL,
23738                                                               MVT::i8));
23739
23740           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23741           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23742
23743           if (is64BitFP && !Subtarget->is64Bit()) {
23744             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23745             // 64-bit integer, since that's not a legal type. Since
23746             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23747             // bits, but can do this little dance to extract the lowest 32 bits
23748             // and work with those going forward.
23749             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23750                                            OnesOrZeroesF);
23751             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23752             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23753                                         Vector32, DAG.getIntPtrConstant(0, DL));
23754             IntVT = MVT::i32;
23755           }
23756
23757           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23758           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23759                                       DAG.getConstant(1, DL, IntVT));
23760           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23761                                               ANDed);
23762           return OneBitOfTruth;
23763         }
23764       }
23765     }
23766   }
23767   return SDValue();
23768 }
23769
23770 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23771 /// so it can be folded inside ANDNP.
23772 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23773   EVT VT = N->getValueType(0);
23774
23775   // Match direct AllOnes for 128 and 256-bit vectors
23776   if (ISD::isBuildVectorAllOnes(N))
23777     return true;
23778
23779   // Look through a bit convert.
23780   if (N->getOpcode() == ISD::BITCAST)
23781     N = N->getOperand(0).getNode();
23782
23783   // Sometimes the operand may come from a insert_subvector building a 256-bit
23784   // allones vector
23785   if (VT.is256BitVector() &&
23786       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23787     SDValue V1 = N->getOperand(0);
23788     SDValue V2 = N->getOperand(1);
23789
23790     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23791         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23792         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23793         ISD::isBuildVectorAllOnes(V2.getNode()))
23794       return true;
23795   }
23796
23797   return false;
23798 }
23799
23800 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23801 // register. In most cases we actually compare or select YMM-sized registers
23802 // and mixing the two types creates horrible code. This method optimizes
23803 // some of the transition sequences.
23804 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23805                                  TargetLowering::DAGCombinerInfo &DCI,
23806                                  const X86Subtarget *Subtarget) {
23807   EVT VT = N->getValueType(0);
23808   if (!VT.is256BitVector())
23809     return SDValue();
23810
23811   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23812           N->getOpcode() == ISD::ZERO_EXTEND ||
23813           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23814
23815   SDValue Narrow = N->getOperand(0);
23816   EVT NarrowVT = Narrow->getValueType(0);
23817   if (!NarrowVT.is128BitVector())
23818     return SDValue();
23819
23820   if (Narrow->getOpcode() != ISD::XOR &&
23821       Narrow->getOpcode() != ISD::AND &&
23822       Narrow->getOpcode() != ISD::OR)
23823     return SDValue();
23824
23825   SDValue N0  = Narrow->getOperand(0);
23826   SDValue N1  = Narrow->getOperand(1);
23827   SDLoc DL(Narrow);
23828
23829   // The Left side has to be a trunc.
23830   if (N0.getOpcode() != ISD::TRUNCATE)
23831     return SDValue();
23832
23833   // The type of the truncated inputs.
23834   EVT WideVT = N0->getOperand(0)->getValueType(0);
23835   if (WideVT != VT)
23836     return SDValue();
23837
23838   // The right side has to be a 'trunc' or a constant vector.
23839   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23840   ConstantSDNode *RHSConstSplat = nullptr;
23841   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23842     RHSConstSplat = RHSBV->getConstantSplatNode();
23843   if (!RHSTrunc && !RHSConstSplat)
23844     return SDValue();
23845
23846   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23847
23848   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23849     return SDValue();
23850
23851   // Set N0 and N1 to hold the inputs to the new wide operation.
23852   N0 = N0->getOperand(0);
23853   if (RHSConstSplat) {
23854     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23855                      SDValue(RHSConstSplat, 0));
23856     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23857     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23858   } else if (RHSTrunc) {
23859     N1 = N1->getOperand(0);
23860   }
23861
23862   // Generate the wide operation.
23863   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23864   unsigned Opcode = N->getOpcode();
23865   switch (Opcode) {
23866   case ISD::ANY_EXTEND:
23867     return Op;
23868   case ISD::ZERO_EXTEND: {
23869     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23870     APInt Mask = APInt::getAllOnesValue(InBits);
23871     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23872     return DAG.getNode(ISD::AND, DL, VT,
23873                        Op, DAG.getConstant(Mask, DL, VT));
23874   }
23875   case ISD::SIGN_EXTEND:
23876     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23877                        Op, DAG.getValueType(NarrowVT));
23878   default:
23879     llvm_unreachable("Unexpected opcode");
23880   }
23881 }
23882
23883 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23884                                  TargetLowering::DAGCombinerInfo &DCI,
23885                                  const X86Subtarget *Subtarget) {
23886   SDValue N0 = N->getOperand(0);
23887   SDValue N1 = N->getOperand(1);
23888   SDLoc DL(N);
23889
23890   // A vector zext_in_reg may be represented as a shuffle,
23891   // feeding into a bitcast (this represents anyext) feeding into
23892   // an and with a mask.
23893   // We'd like to try to combine that into a shuffle with zero
23894   // plus a bitcast, removing the and.
23895   if (N0.getOpcode() != ISD::BITCAST ||
23896       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23897     return SDValue();
23898
23899   // The other side of the AND should be a splat of 2^C, where C
23900   // is the number of bits in the source type.
23901   if (N1.getOpcode() == ISD::BITCAST)
23902     N1 = N1.getOperand(0);
23903   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23904     return SDValue();
23905   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23906
23907   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23908   EVT SrcType = Shuffle->getValueType(0);
23909
23910   // We expect a single-source shuffle
23911   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23912     return SDValue();
23913
23914   unsigned SrcSize = SrcType.getScalarSizeInBits();
23915
23916   APInt SplatValue, SplatUndef;
23917   unsigned SplatBitSize;
23918   bool HasAnyUndefs;
23919   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23920                                 SplatBitSize, HasAnyUndefs))
23921     return SDValue();
23922
23923   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23924   // Make sure the splat matches the mask we expect
23925   if (SplatBitSize > ResSize ||
23926       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23927     return SDValue();
23928
23929   // Make sure the input and output size make sense
23930   if (SrcSize >= ResSize || ResSize % SrcSize)
23931     return SDValue();
23932
23933   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23934   // The number of u's between each two values depends on the ratio between
23935   // the source and dest type.
23936   unsigned ZextRatio = ResSize / SrcSize;
23937   bool IsZext = true;
23938   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23939     if (i % ZextRatio) {
23940       if (Shuffle->getMaskElt(i) > 0) {
23941         // Expected undef
23942         IsZext = false;
23943         break;
23944       }
23945     } else {
23946       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23947         // Expected element number
23948         IsZext = false;
23949         break;
23950       }
23951     }
23952   }
23953
23954   if (!IsZext)
23955     return SDValue();
23956
23957   // Ok, perform the transformation - replace the shuffle with
23958   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23959   // (instead of undef) where the k elements come from the zero vector.
23960   SmallVector<int, 8> Mask;
23961   unsigned NumElems = SrcType.getVectorNumElements();
23962   for (unsigned i = 0; i < NumElems; ++i)
23963     if (i % ZextRatio)
23964       Mask.push_back(NumElems);
23965     else
23966       Mask.push_back(i / ZextRatio);
23967
23968   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23969     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23970   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23971 }
23972
23973 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23974                                  TargetLowering::DAGCombinerInfo &DCI,
23975                                  const X86Subtarget *Subtarget) {
23976   if (DCI.isBeforeLegalizeOps())
23977     return SDValue();
23978
23979   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23980     return Zext;
23981
23982   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23983     return R;
23984
23985   EVT VT = N->getValueType(0);
23986   SDValue N0 = N->getOperand(0);
23987   SDValue N1 = N->getOperand(1);
23988   SDLoc DL(N);
23989
23990   // Create BEXTR instructions
23991   // BEXTR is ((X >> imm) & (2**size-1))
23992   if (VT == MVT::i32 || VT == MVT::i64) {
23993     // Check for BEXTR.
23994     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23995         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23996       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23997       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23998       if (MaskNode && ShiftNode) {
23999         uint64_t Mask = MaskNode->getZExtValue();
24000         uint64_t Shift = ShiftNode->getZExtValue();
24001         if (isMask_64(Mask)) {
24002           uint64_t MaskSize = countPopulation(Mask);
24003           if (Shift + MaskSize <= VT.getSizeInBits())
24004             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24005                                DAG.getConstant(Shift | (MaskSize << 8), DL,
24006                                                VT));
24007         }
24008       }
24009     } // BEXTR
24010
24011     return SDValue();
24012   }
24013
24014   // Want to form ANDNP nodes:
24015   // 1) In the hopes of then easily combining them with OR and AND nodes
24016   //    to form PBLEND/PSIGN.
24017   // 2) To match ANDN packed intrinsics
24018   if (VT != MVT::v2i64 && VT != MVT::v4i64)
24019     return SDValue();
24020
24021   // Check LHS for vnot
24022   if (N0.getOpcode() == ISD::XOR &&
24023       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24024       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24025     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24026
24027   // Check RHS for vnot
24028   if (N1.getOpcode() == ISD::XOR &&
24029       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24030       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24031     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24032
24033   return SDValue();
24034 }
24035
24036 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24037                                 TargetLowering::DAGCombinerInfo &DCI,
24038                                 const X86Subtarget *Subtarget) {
24039   if (DCI.isBeforeLegalizeOps())
24040     return SDValue();
24041
24042   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24043     return R;
24044
24045   SDValue N0 = N->getOperand(0);
24046   SDValue N1 = N->getOperand(1);
24047   EVT VT = N->getValueType(0);
24048
24049   // look for psign/blend
24050   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24051     if (!Subtarget->hasSSSE3() ||
24052         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24053       return SDValue();
24054
24055     // Canonicalize pandn to RHS
24056     if (N0.getOpcode() == X86ISD::ANDNP)
24057       std::swap(N0, N1);
24058     // or (and (m, y), (pandn m, x))
24059     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24060       SDValue Mask = N1.getOperand(0);
24061       SDValue X    = N1.getOperand(1);
24062       SDValue Y;
24063       if (N0.getOperand(0) == Mask)
24064         Y = N0.getOperand(1);
24065       if (N0.getOperand(1) == Mask)
24066         Y = N0.getOperand(0);
24067
24068       // Check to see if the mask appeared in both the AND and ANDNP and
24069       if (!Y.getNode())
24070         return SDValue();
24071
24072       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24073       // Look through mask bitcast.
24074       if (Mask.getOpcode() == ISD::BITCAST)
24075         Mask = Mask.getOperand(0);
24076       if (X.getOpcode() == ISD::BITCAST)
24077         X = X.getOperand(0);
24078       if (Y.getOpcode() == ISD::BITCAST)
24079         Y = Y.getOperand(0);
24080
24081       EVT MaskVT = Mask.getValueType();
24082
24083       // Validate that the Mask operand is a vector sra node.
24084       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24085       // there is no psrai.b
24086       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24087       unsigned SraAmt = ~0;
24088       if (Mask.getOpcode() == ISD::SRA) {
24089         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24090           if (auto *AmtConst = AmtBV->getConstantSplatNode())
24091             SraAmt = AmtConst->getZExtValue();
24092       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24093         SDValue SraC = Mask.getOperand(1);
24094         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
24095       }
24096       if ((SraAmt + 1) != EltBits)
24097         return SDValue();
24098
24099       SDLoc DL(N);
24100
24101       // Now we know we at least have a plendvb with the mask val.  See if
24102       // we can form a psignb/w/d.
24103       // psign = x.type == y.type == mask.type && y = sub(0, x);
24104       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24105           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24106           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24107         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24108                "Unsupported VT for PSIGN");
24109         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24110         return DAG.getBitcast(VT, Mask);
24111       }
24112       // PBLENDVB only available on SSE 4.1
24113       if (!Subtarget->hasSSE41())
24114         return SDValue();
24115
24116       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24117
24118       X = DAG.getBitcast(BlendVT, X);
24119       Y = DAG.getBitcast(BlendVT, Y);
24120       Mask = DAG.getBitcast(BlendVT, Mask);
24121       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24122       return DAG.getBitcast(VT, Mask);
24123     }
24124   }
24125
24126   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24127     return SDValue();
24128
24129   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24130   bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24131
24132   // SHLD/SHRD instructions have lower register pressure, but on some
24133   // platforms they have higher latency than the equivalent
24134   // series of shifts/or that would otherwise be generated.
24135   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24136   // have higher latencies and we are not optimizing for size.
24137   if (!OptForSize && Subtarget->isSHLDSlow())
24138     return SDValue();
24139
24140   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24141     std::swap(N0, N1);
24142   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24143     return SDValue();
24144   if (!N0.hasOneUse() || !N1.hasOneUse())
24145     return SDValue();
24146
24147   SDValue ShAmt0 = N0.getOperand(1);
24148   if (ShAmt0.getValueType() != MVT::i8)
24149     return SDValue();
24150   SDValue ShAmt1 = N1.getOperand(1);
24151   if (ShAmt1.getValueType() != MVT::i8)
24152     return SDValue();
24153   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24154     ShAmt0 = ShAmt0.getOperand(0);
24155   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24156     ShAmt1 = ShAmt1.getOperand(0);
24157
24158   SDLoc DL(N);
24159   unsigned Opc = X86ISD::SHLD;
24160   SDValue Op0 = N0.getOperand(0);
24161   SDValue Op1 = N1.getOperand(0);
24162   if (ShAmt0.getOpcode() == ISD::SUB) {
24163     Opc = X86ISD::SHRD;
24164     std::swap(Op0, Op1);
24165     std::swap(ShAmt0, ShAmt1);
24166   }
24167
24168   unsigned Bits = VT.getSizeInBits();
24169   if (ShAmt1.getOpcode() == ISD::SUB) {
24170     SDValue Sum = ShAmt1.getOperand(0);
24171     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24172       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24173       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24174         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24175       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24176         return DAG.getNode(Opc, DL, VT,
24177                            Op0, Op1,
24178                            DAG.getNode(ISD::TRUNCATE, DL,
24179                                        MVT::i8, ShAmt0));
24180     }
24181   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24182     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24183     if (ShAmt0C &&
24184         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24185       return DAG.getNode(Opc, DL, VT,
24186                          N0.getOperand(0), N1.getOperand(0),
24187                          DAG.getNode(ISD::TRUNCATE, DL,
24188                                        MVT::i8, ShAmt0));
24189   }
24190
24191   return SDValue();
24192 }
24193
24194 // Generate NEG and CMOV for integer abs.
24195 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24196   EVT VT = N->getValueType(0);
24197
24198   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24199   // 8-bit integer abs to NEG and CMOV.
24200   if (VT.isInteger() && VT.getSizeInBits() == 8)
24201     return SDValue();
24202
24203   SDValue N0 = N->getOperand(0);
24204   SDValue N1 = N->getOperand(1);
24205   SDLoc DL(N);
24206
24207   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24208   // and change it to SUB and CMOV.
24209   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24210       N0.getOpcode() == ISD::ADD &&
24211       N0.getOperand(1) == N1 &&
24212       N1.getOpcode() == ISD::SRA &&
24213       N1.getOperand(0) == N0.getOperand(0))
24214     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24215       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24216         // Generate SUB & CMOV.
24217         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24218                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24219
24220         SDValue Ops[] = { N0.getOperand(0), Neg,
24221                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24222                           SDValue(Neg.getNode(), 1) };
24223         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24224       }
24225   return SDValue();
24226 }
24227
24228 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24229 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24230                                  TargetLowering::DAGCombinerInfo &DCI,
24231                                  const X86Subtarget *Subtarget) {
24232   if (DCI.isBeforeLegalizeOps())
24233     return SDValue();
24234
24235   if (Subtarget->hasCMov())
24236     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24237       return RV;
24238
24239   return SDValue();
24240 }
24241
24242 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24243 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24244                                   TargetLowering::DAGCombinerInfo &DCI,
24245                                   const X86Subtarget *Subtarget) {
24246   LoadSDNode *Ld = cast<LoadSDNode>(N);
24247   EVT RegVT = Ld->getValueType(0);
24248   EVT MemVT = Ld->getMemoryVT();
24249   SDLoc dl(Ld);
24250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24251
24252   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24253   // into two 16-byte operations.
24254   ISD::LoadExtType Ext = Ld->getExtensionType();
24255   unsigned Alignment = Ld->getAlignment();
24256   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24257   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24258       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24259     unsigned NumElems = RegVT.getVectorNumElements();
24260     if (NumElems < 2)
24261       return SDValue();
24262
24263     SDValue Ptr = Ld->getBasePtr();
24264     SDValue Increment =
24265         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24266
24267     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24268                                   NumElems/2);
24269     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24270                                 Ld->getPointerInfo(), Ld->isVolatile(),
24271                                 Ld->isNonTemporal(), Ld->isInvariant(),
24272                                 Alignment);
24273     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24274     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24275                                 Ld->getPointerInfo(), Ld->isVolatile(),
24276                                 Ld->isNonTemporal(), Ld->isInvariant(),
24277                                 std::min(16U, Alignment));
24278     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24279                              Load1.getValue(1),
24280                              Load2.getValue(1));
24281
24282     SDValue NewVec = DAG.getUNDEF(RegVT);
24283     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24284     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24285     return DCI.CombineTo(N, NewVec, TF, true);
24286   }
24287
24288   return SDValue();
24289 }
24290
24291 /// PerformMLOADCombine - Resolve extending loads
24292 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24293                                    TargetLowering::DAGCombinerInfo &DCI,
24294                                    const X86Subtarget *Subtarget) {
24295   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24296   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24297     return SDValue();
24298
24299   EVT VT = Mld->getValueType(0);
24300   unsigned NumElems = VT.getVectorNumElements();
24301   EVT LdVT = Mld->getMemoryVT();
24302   SDLoc dl(Mld);
24303
24304   assert(LdVT != VT && "Cannot extend to the same type");
24305   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24306   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24307   // From, To sizes and ElemCount must be pow of two
24308   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24309     "Unexpected size for extending masked load");
24310
24311   unsigned SizeRatio  = ToSz / FromSz;
24312   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24313
24314   // Create a type on which we perform the shuffle
24315   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24316           LdVT.getScalarType(), NumElems*SizeRatio);
24317   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24318
24319   // Convert Src0 value
24320   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24321   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24322     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24323     for (unsigned i = 0; i != NumElems; ++i)
24324       ShuffleVec[i] = i * SizeRatio;
24325
24326     // Can't shuffle using an illegal type.
24327     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24328             && "WideVecVT should be legal");
24329     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24330                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24331   }
24332   // Prepare the new mask
24333   SDValue NewMask;
24334   SDValue Mask = Mld->getMask();
24335   if (Mask.getValueType() == VT) {
24336     // Mask and original value have the same type
24337     NewMask = DAG.getBitcast(WideVecVT, Mask);
24338     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24339     for (unsigned i = 0; i != NumElems; ++i)
24340       ShuffleVec[i] = i * SizeRatio;
24341     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24342       ShuffleVec[i] = NumElems*SizeRatio;
24343     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24344                                    DAG.getConstant(0, dl, WideVecVT),
24345                                    &ShuffleVec[0]);
24346   }
24347   else {
24348     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24349     unsigned WidenNumElts = NumElems*SizeRatio;
24350     unsigned MaskNumElts = VT.getVectorNumElements();
24351     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24352                                      WidenNumElts);
24353
24354     unsigned NumConcat = WidenNumElts / MaskNumElts;
24355     SmallVector<SDValue, 16> Ops(NumConcat);
24356     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24357     Ops[0] = Mask;
24358     for (unsigned i = 1; i != NumConcat; ++i)
24359       Ops[i] = ZeroVal;
24360
24361     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24362   }
24363
24364   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24365                                      Mld->getBasePtr(), NewMask, WideSrc0,
24366                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24367                                      ISD::NON_EXTLOAD);
24368   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24369   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24370
24371 }
24372 /// PerformMSTORECombine - Resolve truncating stores
24373 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24374                                     const X86Subtarget *Subtarget) {
24375   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24376   if (!Mst->isTruncatingStore())
24377     return SDValue();
24378
24379   EVT VT = Mst->getValue().getValueType();
24380   unsigned NumElems = VT.getVectorNumElements();
24381   EVT StVT = Mst->getMemoryVT();
24382   SDLoc dl(Mst);
24383
24384   assert(StVT != VT && "Cannot truncate to the same type");
24385   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24386   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24387
24388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24389
24390   // The truncating store is legal in some cases. For example
24391   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24392   // are designated for truncate store.
24393   // In this case we don't need any further transformations.
24394   if (TLI.isTruncStoreLegal(VT, StVT))
24395     return SDValue();
24396
24397   // From, To sizes and ElemCount must be pow of two
24398   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24399     "Unexpected size for truncating masked store");
24400   // We are going to use the original vector elt for storing.
24401   // Accumulated smaller vector elements must be a multiple of the store size.
24402   assert (((NumElems * FromSz) % ToSz) == 0 &&
24403           "Unexpected ratio for truncating masked store");
24404
24405   unsigned SizeRatio  = FromSz / ToSz;
24406   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24407
24408   // Create a type on which we perform the shuffle
24409   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24410           StVT.getScalarType(), NumElems*SizeRatio);
24411
24412   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24413
24414   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24415   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24416   for (unsigned i = 0; i != NumElems; ++i)
24417     ShuffleVec[i] = i * SizeRatio;
24418
24419   // Can't shuffle using an illegal type.
24420   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24421           && "WideVecVT should be legal");
24422
24423   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24424                                         DAG.getUNDEF(WideVecVT),
24425                                         &ShuffleVec[0]);
24426
24427   SDValue NewMask;
24428   SDValue Mask = Mst->getMask();
24429   if (Mask.getValueType() == VT) {
24430     // Mask and original value have the same type
24431     NewMask = DAG.getBitcast(WideVecVT, Mask);
24432     for (unsigned i = 0; i != NumElems; ++i)
24433       ShuffleVec[i] = i * SizeRatio;
24434     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24435       ShuffleVec[i] = NumElems*SizeRatio;
24436     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24437                                    DAG.getConstant(0, dl, WideVecVT),
24438                                    &ShuffleVec[0]);
24439   }
24440   else {
24441     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24442     unsigned WidenNumElts = NumElems*SizeRatio;
24443     unsigned MaskNumElts = VT.getVectorNumElements();
24444     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24445                                      WidenNumElts);
24446
24447     unsigned NumConcat = WidenNumElts / MaskNumElts;
24448     SmallVector<SDValue, 16> Ops(NumConcat);
24449     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24450     Ops[0] = Mask;
24451     for (unsigned i = 1; i != NumConcat; ++i)
24452       Ops[i] = ZeroVal;
24453
24454     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24455   }
24456
24457   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24458                             NewMask, StVT, Mst->getMemOperand(), false);
24459 }
24460 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24461 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24462                                    const X86Subtarget *Subtarget) {
24463   StoreSDNode *St = cast<StoreSDNode>(N);
24464   EVT VT = St->getValue().getValueType();
24465   EVT StVT = St->getMemoryVT();
24466   SDLoc dl(St);
24467   SDValue StoredVal = St->getOperand(1);
24468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24469
24470   // If we are saving a concatenation of two XMM registers and 32-byte stores
24471   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24472   unsigned Alignment = St->getAlignment();
24473   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24474   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24475       StVT == VT && !IsAligned) {
24476     unsigned NumElems = VT.getVectorNumElements();
24477     if (NumElems < 2)
24478       return SDValue();
24479
24480     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24481     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24482
24483     SDValue Stride =
24484         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24485     SDValue Ptr0 = St->getBasePtr();
24486     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24487
24488     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24489                                 St->getPointerInfo(), St->isVolatile(),
24490                                 St->isNonTemporal(), Alignment);
24491     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24492                                 St->getPointerInfo(), St->isVolatile(),
24493                                 St->isNonTemporal(),
24494                                 std::min(16U, Alignment));
24495     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24496   }
24497
24498   // Optimize trunc store (of multiple scalars) to shuffle and store.
24499   // First, pack all of the elements in one place. Next, store to memory
24500   // in fewer chunks.
24501   if (St->isTruncatingStore() && VT.isVector()) {
24502     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24503     unsigned NumElems = VT.getVectorNumElements();
24504     assert(StVT != VT && "Cannot truncate to the same type");
24505     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24506     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24507
24508     // The truncating store is legal in some cases. For example
24509     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24510     // are designated for truncate store.
24511     // In this case we don't need any further transformations.
24512     if (TLI.isTruncStoreLegal(VT, StVT))
24513       return SDValue();
24514
24515     // From, To sizes and ElemCount must be pow of two
24516     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24517     // We are going to use the original vector elt for storing.
24518     // Accumulated smaller vector elements must be a multiple of the store size.
24519     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24520
24521     unsigned SizeRatio  = FromSz / ToSz;
24522
24523     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24524
24525     // Create a type on which we perform the shuffle
24526     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24527             StVT.getScalarType(), NumElems*SizeRatio);
24528
24529     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24530
24531     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24532     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24533     for (unsigned i = 0; i != NumElems; ++i)
24534       ShuffleVec[i] = i * SizeRatio;
24535
24536     // Can't shuffle using an illegal type.
24537     if (!TLI.isTypeLegal(WideVecVT))
24538       return SDValue();
24539
24540     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24541                                          DAG.getUNDEF(WideVecVT),
24542                                          &ShuffleVec[0]);
24543     // At this point all of the data is stored at the bottom of the
24544     // register. We now need to save it to mem.
24545
24546     // Find the largest store unit
24547     MVT StoreType = MVT::i8;
24548     for (MVT Tp : MVT::integer_valuetypes()) {
24549       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24550         StoreType = Tp;
24551     }
24552
24553     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24554     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24555         (64 <= NumElems * ToSz))
24556       StoreType = MVT::f64;
24557
24558     // Bitcast the original vector into a vector of store-size units
24559     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24560             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24561     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24562     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24563     SmallVector<SDValue, 8> Chains;
24564     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24565                                         TLI.getPointerTy(DAG.getDataLayout()));
24566     SDValue Ptr = St->getBasePtr();
24567
24568     // Perform one or more big stores into memory.
24569     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24570       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24571                                    StoreType, ShuffWide,
24572                                    DAG.getIntPtrConstant(i, dl));
24573       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24574                                 St->getPointerInfo(), St->isVolatile(),
24575                                 St->isNonTemporal(), St->getAlignment());
24576       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24577       Chains.push_back(Ch);
24578     }
24579
24580     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24581   }
24582
24583   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24584   // the FP state in cases where an emms may be missing.
24585   // A preferable solution to the general problem is to figure out the right
24586   // places to insert EMMS.  This qualifies as a quick hack.
24587
24588   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24589   if (VT.getSizeInBits() != 64)
24590     return SDValue();
24591
24592   const Function *F = DAG.getMachineFunction().getFunction();
24593   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24594   bool F64IsLegal =
24595       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24596   if ((VT.isVector() ||
24597        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24598       isa<LoadSDNode>(St->getValue()) &&
24599       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24600       St->getChain().hasOneUse() && !St->isVolatile()) {
24601     SDNode* LdVal = St->getValue().getNode();
24602     LoadSDNode *Ld = nullptr;
24603     int TokenFactorIndex = -1;
24604     SmallVector<SDValue, 8> Ops;
24605     SDNode* ChainVal = St->getChain().getNode();
24606     // Must be a store of a load.  We currently handle two cases:  the load
24607     // is a direct child, and it's under an intervening TokenFactor.  It is
24608     // possible to dig deeper under nested TokenFactors.
24609     if (ChainVal == LdVal)
24610       Ld = cast<LoadSDNode>(St->getChain());
24611     else if (St->getValue().hasOneUse() &&
24612              ChainVal->getOpcode() == ISD::TokenFactor) {
24613       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24614         if (ChainVal->getOperand(i).getNode() == LdVal) {
24615           TokenFactorIndex = i;
24616           Ld = cast<LoadSDNode>(St->getValue());
24617         } else
24618           Ops.push_back(ChainVal->getOperand(i));
24619       }
24620     }
24621
24622     if (!Ld || !ISD::isNormalLoad(Ld))
24623       return SDValue();
24624
24625     // If this is not the MMX case, i.e. we are just turning i64 load/store
24626     // into f64 load/store, avoid the transformation if there are multiple
24627     // uses of the loaded value.
24628     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24629       return SDValue();
24630
24631     SDLoc LdDL(Ld);
24632     SDLoc StDL(N);
24633     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24634     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24635     // pair instead.
24636     if (Subtarget->is64Bit() || F64IsLegal) {
24637       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24638       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24639                                   Ld->getPointerInfo(), Ld->isVolatile(),
24640                                   Ld->isNonTemporal(), Ld->isInvariant(),
24641                                   Ld->getAlignment());
24642       SDValue NewChain = NewLd.getValue(1);
24643       if (TokenFactorIndex != -1) {
24644         Ops.push_back(NewChain);
24645         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24646       }
24647       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24648                           St->getPointerInfo(),
24649                           St->isVolatile(), St->isNonTemporal(),
24650                           St->getAlignment());
24651     }
24652
24653     // Otherwise, lower to two pairs of 32-bit loads / stores.
24654     SDValue LoAddr = Ld->getBasePtr();
24655     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24656                                  DAG.getConstant(4, LdDL, MVT::i32));
24657
24658     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24659                                Ld->getPointerInfo(),
24660                                Ld->isVolatile(), Ld->isNonTemporal(),
24661                                Ld->isInvariant(), Ld->getAlignment());
24662     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24663                                Ld->getPointerInfo().getWithOffset(4),
24664                                Ld->isVolatile(), Ld->isNonTemporal(),
24665                                Ld->isInvariant(),
24666                                MinAlign(Ld->getAlignment(), 4));
24667
24668     SDValue NewChain = LoLd.getValue(1);
24669     if (TokenFactorIndex != -1) {
24670       Ops.push_back(LoLd);
24671       Ops.push_back(HiLd);
24672       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24673     }
24674
24675     LoAddr = St->getBasePtr();
24676     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24677                          DAG.getConstant(4, StDL, MVT::i32));
24678
24679     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24680                                 St->getPointerInfo(),
24681                                 St->isVolatile(), St->isNonTemporal(),
24682                                 St->getAlignment());
24683     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24684                                 St->getPointerInfo().getWithOffset(4),
24685                                 St->isVolatile(),
24686                                 St->isNonTemporal(),
24687                                 MinAlign(St->getAlignment(), 4));
24688     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24689   }
24690
24691   // This is similar to the above case, but here we handle a scalar 64-bit
24692   // integer store that is extracted from a vector on a 32-bit target.
24693   // If we have SSE2, then we can treat it like a floating-point double
24694   // to get past legalization. The execution dependencies fixup pass will
24695   // choose the optimal machine instruction for the store if this really is
24696   // an integer or v2f32 rather than an f64.
24697   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24698       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24699     SDValue OldExtract = St->getOperand(1);
24700     SDValue ExtOp0 = OldExtract.getOperand(0);
24701     unsigned VecSize = ExtOp0.getValueSizeInBits();
24702     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24703     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24704     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24705                                      BitCast, OldExtract.getOperand(1));
24706     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24707                         St->getPointerInfo(), St->isVolatile(),
24708                         St->isNonTemporal(), St->getAlignment());
24709   }
24710
24711   return SDValue();
24712 }
24713
24714 /// Return 'true' if this vector operation is "horizontal"
24715 /// and return the operands for the horizontal operation in LHS and RHS.  A
24716 /// horizontal operation performs the binary operation on successive elements
24717 /// of its first operand, then on successive elements of its second operand,
24718 /// returning the resulting values in a vector.  For example, if
24719 ///   A = < float a0, float a1, float a2, float a3 >
24720 /// and
24721 ///   B = < float b0, float b1, float b2, float b3 >
24722 /// then the result of doing a horizontal operation on A and B is
24723 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24724 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24725 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24726 /// set to A, RHS to B, and the routine returns 'true'.
24727 /// Note that the binary operation should have the property that if one of the
24728 /// operands is UNDEF then the result is UNDEF.
24729 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24730   // Look for the following pattern: if
24731   //   A = < float a0, float a1, float a2, float a3 >
24732   //   B = < float b0, float b1, float b2, float b3 >
24733   // and
24734   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24735   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24736   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24737   // which is A horizontal-op B.
24738
24739   // At least one of the operands should be a vector shuffle.
24740   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24741       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24742     return false;
24743
24744   MVT VT = LHS.getSimpleValueType();
24745
24746   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24747          "Unsupported vector type for horizontal add/sub");
24748
24749   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24750   // operate independently on 128-bit lanes.
24751   unsigned NumElts = VT.getVectorNumElements();
24752   unsigned NumLanes = VT.getSizeInBits()/128;
24753   unsigned NumLaneElts = NumElts / NumLanes;
24754   assert((NumLaneElts % 2 == 0) &&
24755          "Vector type should have an even number of elements in each lane");
24756   unsigned HalfLaneElts = NumLaneElts/2;
24757
24758   // View LHS in the form
24759   //   LHS = VECTOR_SHUFFLE A, B, LMask
24760   // If LHS is not a shuffle then pretend it is the shuffle
24761   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24762   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24763   // type VT.
24764   SDValue A, B;
24765   SmallVector<int, 16> LMask(NumElts);
24766   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24767     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24768       A = LHS.getOperand(0);
24769     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24770       B = LHS.getOperand(1);
24771     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24772     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24773   } else {
24774     if (LHS.getOpcode() != ISD::UNDEF)
24775       A = LHS;
24776     for (unsigned i = 0; i != NumElts; ++i)
24777       LMask[i] = i;
24778   }
24779
24780   // Likewise, view RHS in the form
24781   //   RHS = VECTOR_SHUFFLE C, D, RMask
24782   SDValue C, D;
24783   SmallVector<int, 16> RMask(NumElts);
24784   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24785     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24786       C = RHS.getOperand(0);
24787     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24788       D = RHS.getOperand(1);
24789     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24790     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24791   } else {
24792     if (RHS.getOpcode() != ISD::UNDEF)
24793       C = RHS;
24794     for (unsigned i = 0; i != NumElts; ++i)
24795       RMask[i] = i;
24796   }
24797
24798   // Check that the shuffles are both shuffling the same vectors.
24799   if (!(A == C && B == D) && !(A == D && B == C))
24800     return false;
24801
24802   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24803   if (!A.getNode() && !B.getNode())
24804     return false;
24805
24806   // If A and B occur in reverse order in RHS, then "swap" them (which means
24807   // rewriting the mask).
24808   if (A != C)
24809     ShuffleVectorSDNode::commuteMask(RMask);
24810
24811   // At this point LHS and RHS are equivalent to
24812   //   LHS = VECTOR_SHUFFLE A, B, LMask
24813   //   RHS = VECTOR_SHUFFLE A, B, RMask
24814   // Check that the masks correspond to performing a horizontal operation.
24815   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24816     for (unsigned i = 0; i != NumLaneElts; ++i) {
24817       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24818
24819       // Ignore any UNDEF components.
24820       if (LIdx < 0 || RIdx < 0 ||
24821           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24822           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24823         continue;
24824
24825       // Check that successive elements are being operated on.  If not, this is
24826       // not a horizontal operation.
24827       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24828       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24829       if (!(LIdx == Index && RIdx == Index + 1) &&
24830           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24831         return false;
24832     }
24833   }
24834
24835   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24836   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24837   return true;
24838 }
24839
24840 /// Do target-specific dag combines on floating point adds.
24841 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24842                                   const X86Subtarget *Subtarget) {
24843   EVT VT = N->getValueType(0);
24844   SDValue LHS = N->getOperand(0);
24845   SDValue RHS = N->getOperand(1);
24846
24847   // Try to synthesize horizontal adds from adds of shuffles.
24848   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24849        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24850       isHorizontalBinOp(LHS, RHS, true))
24851     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24852   return SDValue();
24853 }
24854
24855 /// Do target-specific dag combines on floating point subs.
24856 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24857                                   const X86Subtarget *Subtarget) {
24858   EVT VT = N->getValueType(0);
24859   SDValue LHS = N->getOperand(0);
24860   SDValue RHS = N->getOperand(1);
24861
24862   // Try to synthesize horizontal subs from subs of shuffles.
24863   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24864        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24865       isHorizontalBinOp(LHS, RHS, false))
24866     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24867   return SDValue();
24868 }
24869
24870 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24871 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24872   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24873
24874   // F[X]OR(0.0, x) -> x
24875   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24876     if (C->getValueAPF().isPosZero())
24877       return N->getOperand(1);
24878
24879   // F[X]OR(x, 0.0) -> x
24880   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24881     if (C->getValueAPF().isPosZero())
24882       return N->getOperand(0);
24883   return SDValue();
24884 }
24885
24886 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24887 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24888   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24889
24890   // Only perform optimizations if UnsafeMath is used.
24891   if (!DAG.getTarget().Options.UnsafeFPMath)
24892     return SDValue();
24893
24894   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24895   // into FMINC and FMAXC, which are Commutative operations.
24896   unsigned NewOp = 0;
24897   switch (N->getOpcode()) {
24898     default: llvm_unreachable("unknown opcode");
24899     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24900     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24901   }
24902
24903   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24904                      N->getOperand(0), N->getOperand(1));
24905 }
24906
24907 /// Do target-specific dag combines on X86ISD::FAND nodes.
24908 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24909   // FAND(0.0, x) -> 0.0
24910   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24911     if (C->getValueAPF().isPosZero())
24912       return N->getOperand(0);
24913
24914   // FAND(x, 0.0) -> 0.0
24915   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24916     if (C->getValueAPF().isPosZero())
24917       return N->getOperand(1);
24918
24919   return SDValue();
24920 }
24921
24922 /// Do target-specific dag combines on X86ISD::FANDN nodes
24923 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24924   // FANDN(0.0, x) -> x
24925   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24926     if (C->getValueAPF().isPosZero())
24927       return N->getOperand(1);
24928
24929   // FANDN(x, 0.0) -> 0.0
24930   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24931     if (C->getValueAPF().isPosZero())
24932       return N->getOperand(1);
24933
24934   return SDValue();
24935 }
24936
24937 static SDValue PerformBTCombine(SDNode *N,
24938                                 SelectionDAG &DAG,
24939                                 TargetLowering::DAGCombinerInfo &DCI) {
24940   // BT ignores high bits in the bit index operand.
24941   SDValue Op1 = N->getOperand(1);
24942   if (Op1.hasOneUse()) {
24943     unsigned BitWidth = Op1.getValueSizeInBits();
24944     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24945     APInt KnownZero, KnownOne;
24946     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24947                                           !DCI.isBeforeLegalizeOps());
24948     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24949     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24950         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24951       DCI.CommitTargetLoweringOpt(TLO);
24952   }
24953   return SDValue();
24954 }
24955
24956 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24957   SDValue Op = N->getOperand(0);
24958   if (Op.getOpcode() == ISD::BITCAST)
24959     Op = Op.getOperand(0);
24960   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24961   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24962       VT.getVectorElementType().getSizeInBits() ==
24963       OpVT.getVectorElementType().getSizeInBits()) {
24964     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24965   }
24966   return SDValue();
24967 }
24968
24969 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24970                                                const X86Subtarget *Subtarget) {
24971   EVT VT = N->getValueType(0);
24972   if (!VT.isVector())
24973     return SDValue();
24974
24975   SDValue N0 = N->getOperand(0);
24976   SDValue N1 = N->getOperand(1);
24977   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24978   SDLoc dl(N);
24979
24980   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24981   // both SSE and AVX2 since there is no sign-extended shift right
24982   // operation on a vector with 64-bit elements.
24983   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24984   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24985   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24986       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24987     SDValue N00 = N0.getOperand(0);
24988
24989     // EXTLOAD has a better solution on AVX2,
24990     // it may be replaced with X86ISD::VSEXT node.
24991     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24992       if (!ISD::isNormalLoad(N00.getNode()))
24993         return SDValue();
24994
24995     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24996         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24997                                   N00, N1);
24998       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24999     }
25000   }
25001   return SDValue();
25002 }
25003
25004 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25005                                   TargetLowering::DAGCombinerInfo &DCI,
25006                                   const X86Subtarget *Subtarget) {
25007   SDValue N0 = N->getOperand(0);
25008   EVT VT = N->getValueType(0);
25009   EVT SVT = VT.getScalarType();
25010   EVT InVT = N0.getValueType();
25011   EVT InSVT = InVT.getScalarType();
25012   SDLoc DL(N);
25013
25014   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25015   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25016   // This exposes the sext to the sdivrem lowering, so that it directly extends
25017   // from AH (which we otherwise need to do contortions to access).
25018   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25019       InVT == MVT::i8 && VT == MVT::i32) {
25020     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25021     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25022                             N0.getOperand(0), N0.getOperand(1));
25023     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25024     return R.getValue(1);
25025   }
25026
25027   if (!DCI.isBeforeLegalizeOps()) {
25028     if (InVT == MVT::i1) {
25029       SDValue Zero = DAG.getConstant(0, DL, VT);
25030       SDValue AllOnes =
25031         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25032       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25033     }
25034     return SDValue();
25035   }
25036
25037   if (VT.isVector() && Subtarget->hasSSE2()) {
25038     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25039       EVT InVT = N.getValueType();
25040       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25041                                    Size / InVT.getScalarSizeInBits());
25042       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25043                                     DAG.getUNDEF(InVT));
25044       Opnds[0] = N;
25045       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25046     };
25047
25048     // If target-size is less than 128-bits, extend to a type that would extend
25049     // to 128 bits, extend that and extract the original target vector.
25050     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25051         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25052         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25053       unsigned Scale = 128 / VT.getSizeInBits();
25054       EVT ExVT =
25055           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25056       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25057       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25058       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25059                          DAG.getIntPtrConstant(0, DL));
25060     }
25061
25062     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25063     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25064     if (VT.getSizeInBits() == 128 &&
25065         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25066         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25067       SDValue ExOp = ExtendVecSize(DL, N0, 128);
25068       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25069     }
25070
25071     // On pre-AVX2 targets, split into 128-bit nodes of
25072     // ISD::SIGN_EXTEND_VECTOR_INREG.
25073     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25074         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25075         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25076       unsigned NumVecs = VT.getSizeInBits() / 128;
25077       unsigned NumSubElts = 128 / SVT.getSizeInBits();
25078       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25079       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25080
25081       SmallVector<SDValue, 8> Opnds;
25082       for (unsigned i = 0, Offset = 0; i != NumVecs;
25083            ++i, Offset += NumSubElts) {
25084         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25085                                      DAG.getIntPtrConstant(Offset, DL));
25086         SrcVec = ExtendVecSize(DL, SrcVec, 128);
25087         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25088         Opnds.push_back(SrcVec);
25089       }
25090       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25091     }
25092   }
25093
25094   if (!Subtarget->hasFp256())
25095     return SDValue();
25096
25097   if (VT.isVector() && VT.getSizeInBits() == 256)
25098     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25099       return R;
25100
25101   return SDValue();
25102 }
25103
25104 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25105                                  const X86Subtarget* Subtarget) {
25106   SDLoc dl(N);
25107   EVT VT = N->getValueType(0);
25108
25109   // Let legalize expand this if it isn't a legal type yet.
25110   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25111     return SDValue();
25112
25113   EVT ScalarVT = VT.getScalarType();
25114   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25115       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25116        !Subtarget->hasAVX512()))
25117     return SDValue();
25118
25119   SDValue A = N->getOperand(0);
25120   SDValue B = N->getOperand(1);
25121   SDValue C = N->getOperand(2);
25122
25123   bool NegA = (A.getOpcode() == ISD::FNEG);
25124   bool NegB = (B.getOpcode() == ISD::FNEG);
25125   bool NegC = (C.getOpcode() == ISD::FNEG);
25126
25127   // Negative multiplication when NegA xor NegB
25128   bool NegMul = (NegA != NegB);
25129   if (NegA)
25130     A = A.getOperand(0);
25131   if (NegB)
25132     B = B.getOperand(0);
25133   if (NegC)
25134     C = C.getOperand(0);
25135
25136   unsigned Opcode;
25137   if (!NegMul)
25138     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25139   else
25140     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25141
25142   return DAG.getNode(Opcode, dl, VT, A, B, C);
25143 }
25144
25145 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25146                                   TargetLowering::DAGCombinerInfo &DCI,
25147                                   const X86Subtarget *Subtarget) {
25148   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
25149   //           (and (i32 x86isd::setcc_carry), 1)
25150   // This eliminates the zext. This transformation is necessary because
25151   // ISD::SETCC is always legalized to i8.
25152   SDLoc dl(N);
25153   SDValue N0 = N->getOperand(0);
25154   EVT VT = N->getValueType(0);
25155
25156   if (N0.getOpcode() == ISD::AND &&
25157       N0.hasOneUse() &&
25158       N0.getOperand(0).hasOneUse()) {
25159     SDValue N00 = N0.getOperand(0);
25160     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25161       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25162       if (!C || C->getZExtValue() != 1)
25163         return SDValue();
25164       return DAG.getNode(ISD::AND, dl, VT,
25165                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25166                                      N00.getOperand(0), N00.getOperand(1)),
25167                          DAG.getConstant(1, dl, VT));
25168     }
25169   }
25170
25171   if (N0.getOpcode() == ISD::TRUNCATE &&
25172       N0.hasOneUse() &&
25173       N0.getOperand(0).hasOneUse()) {
25174     SDValue N00 = N0.getOperand(0);
25175     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25176       return DAG.getNode(ISD::AND, dl, VT,
25177                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25178                                      N00.getOperand(0), N00.getOperand(1)),
25179                          DAG.getConstant(1, dl, VT));
25180     }
25181   }
25182
25183   if (VT.is256BitVector())
25184     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25185       return R;
25186
25187   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25188   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25189   // This exposes the zext to the udivrem lowering, so that it directly extends
25190   // from AH (which we otherwise need to do contortions to access).
25191   if (N0.getOpcode() == ISD::UDIVREM &&
25192       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25193       (VT == MVT::i32 || VT == MVT::i64)) {
25194     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25195     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25196                             N0.getOperand(0), N0.getOperand(1));
25197     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25198     return R.getValue(1);
25199   }
25200
25201   return SDValue();
25202 }
25203
25204 // Optimize x == -y --> x+y == 0
25205 //          x != -y --> x+y != 0
25206 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25207                                       const X86Subtarget* Subtarget) {
25208   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25209   SDValue LHS = N->getOperand(0);
25210   SDValue RHS = N->getOperand(1);
25211   EVT VT = N->getValueType(0);
25212   SDLoc DL(N);
25213
25214   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25215     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25216       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25217         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25218                                    LHS.getOperand(1));
25219         return DAG.getSetCC(DL, N->getValueType(0), addV,
25220                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25221       }
25222   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25223     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25224       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25225         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25226                                    RHS.getOperand(1));
25227         return DAG.getSetCC(DL, N->getValueType(0), addV,
25228                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25229       }
25230
25231   if (VT.getScalarType() == MVT::i1 &&
25232       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25233     bool IsSEXT0 =
25234         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25235         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25236     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25237
25238     if (!IsSEXT0 || !IsVZero1) {
25239       // Swap the operands and update the condition code.
25240       std::swap(LHS, RHS);
25241       CC = ISD::getSetCCSwappedOperands(CC);
25242
25243       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25244                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25245       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25246     }
25247
25248     if (IsSEXT0 && IsVZero1) {
25249       assert(VT == LHS.getOperand(0).getValueType() &&
25250              "Uexpected operand type");
25251       if (CC == ISD::SETGT)
25252         return DAG.getConstant(0, DL, VT);
25253       if (CC == ISD::SETLE)
25254         return DAG.getConstant(1, DL, VT);
25255       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25256         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25257
25258       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25259              "Unexpected condition code!");
25260       return LHS.getOperand(0);
25261     }
25262   }
25263
25264   return SDValue();
25265 }
25266
25267 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25268                                          SelectionDAG &DAG) {
25269   SDLoc dl(Load);
25270   MVT VT = Load->getSimpleValueType(0);
25271   MVT EVT = VT.getVectorElementType();
25272   SDValue Addr = Load->getOperand(1);
25273   SDValue NewAddr = DAG.getNode(
25274       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25275       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25276                       Addr.getSimpleValueType()));
25277
25278   SDValue NewLoad =
25279       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25280                   DAG.getMachineFunction().getMachineMemOperand(
25281                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25282   return NewLoad;
25283 }
25284
25285 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25286                                       const X86Subtarget *Subtarget) {
25287   SDLoc dl(N);
25288   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25289   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25290          "X86insertps is only defined for v4x32");
25291
25292   SDValue Ld = N->getOperand(1);
25293   if (MayFoldLoad(Ld)) {
25294     // Extract the countS bits from the immediate so we can get the proper
25295     // address when narrowing the vector load to a specific element.
25296     // When the second source op is a memory address, insertps doesn't use
25297     // countS and just gets an f32 from that address.
25298     unsigned DestIndex =
25299         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25300
25301     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25302
25303     // Create this as a scalar to vector to match the instruction pattern.
25304     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25305     // countS bits are ignored when loading from memory on insertps, which
25306     // means we don't need to explicitly set them to 0.
25307     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25308                        LoadScalarToVector, N->getOperand(2));
25309   }
25310   return SDValue();
25311 }
25312
25313 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25314   SDValue V0 = N->getOperand(0);
25315   SDValue V1 = N->getOperand(1);
25316   SDLoc DL(N);
25317   EVT VT = N->getValueType(0);
25318
25319   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25320   // operands and changing the mask to 1. This saves us a bunch of
25321   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25322   // x86InstrInfo knows how to commute this back after instruction selection
25323   // if it would help register allocation.
25324
25325   // TODO: If optimizing for size or a processor that doesn't suffer from
25326   // partial register update stalls, this should be transformed into a MOVSD
25327   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25328
25329   if (VT == MVT::v2f64)
25330     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25331       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25332         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25333         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25334       }
25335
25336   return SDValue();
25337 }
25338
25339 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25340 // as "sbb reg,reg", since it can be extended without zext and produces
25341 // an all-ones bit which is more useful than 0/1 in some cases.
25342 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25343                                MVT VT) {
25344   if (VT == MVT::i8)
25345     return DAG.getNode(ISD::AND, DL, VT,
25346                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25347                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25348                                    EFLAGS),
25349                        DAG.getConstant(1, DL, VT));
25350   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25351   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25352                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25353                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25354                                  EFLAGS));
25355 }
25356
25357 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25358 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25359                                    TargetLowering::DAGCombinerInfo &DCI,
25360                                    const X86Subtarget *Subtarget) {
25361   SDLoc DL(N);
25362   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25363   SDValue EFLAGS = N->getOperand(1);
25364
25365   if (CC == X86::COND_A) {
25366     // Try to convert COND_A into COND_B in an attempt to facilitate
25367     // materializing "setb reg".
25368     //
25369     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25370     // cannot take an immediate as its first operand.
25371     //
25372     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25373         EFLAGS.getValueType().isInteger() &&
25374         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25375       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25376                                    EFLAGS.getNode()->getVTList(),
25377                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25378       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25379       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25380     }
25381   }
25382
25383   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25384   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25385   // cases.
25386   if (CC == X86::COND_B)
25387     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25388
25389   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25390     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25391     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25392   }
25393
25394   return SDValue();
25395 }
25396
25397 // Optimize branch condition evaluation.
25398 //
25399 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25400                                     TargetLowering::DAGCombinerInfo &DCI,
25401                                     const X86Subtarget *Subtarget) {
25402   SDLoc DL(N);
25403   SDValue Chain = N->getOperand(0);
25404   SDValue Dest = N->getOperand(1);
25405   SDValue EFLAGS = N->getOperand(3);
25406   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25407
25408   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25409     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25410     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25411                        Flags);
25412   }
25413
25414   return SDValue();
25415 }
25416
25417 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25418                                                          SelectionDAG &DAG) {
25419   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25420   // optimize away operation when it's from a constant.
25421   //
25422   // The general transformation is:
25423   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25424   //       AND(VECTOR_CMP(x,y), constant2)
25425   //    constant2 = UNARYOP(constant)
25426
25427   // Early exit if this isn't a vector operation, the operand of the
25428   // unary operation isn't a bitwise AND, or if the sizes of the operations
25429   // aren't the same.
25430   EVT VT = N->getValueType(0);
25431   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25432       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25433       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25434     return SDValue();
25435
25436   // Now check that the other operand of the AND is a constant. We could
25437   // make the transformation for non-constant splats as well, but it's unclear
25438   // that would be a benefit as it would not eliminate any operations, just
25439   // perform one more step in scalar code before moving to the vector unit.
25440   if (BuildVectorSDNode *BV =
25441           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25442     // Bail out if the vector isn't a constant.
25443     if (!BV->isConstant())
25444       return SDValue();
25445
25446     // Everything checks out. Build up the new and improved node.
25447     SDLoc DL(N);
25448     EVT IntVT = BV->getValueType(0);
25449     // Create a new constant of the appropriate type for the transformed
25450     // DAG.
25451     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25452     // The AND node needs bitcasts to/from an integer vector type around it.
25453     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25454     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25455                                  N->getOperand(0)->getOperand(0), MaskConst);
25456     SDValue Res = DAG.getBitcast(VT, NewAnd);
25457     return Res;
25458   }
25459
25460   return SDValue();
25461 }
25462
25463 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25464                                         const X86Subtarget *Subtarget) {
25465   SDValue Op0 = N->getOperand(0);
25466   EVT VT = N->getValueType(0);
25467   EVT InVT = Op0.getValueType();
25468   EVT InSVT = InVT.getScalarType();
25469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25470
25471   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25472   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25473   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25474     SDLoc dl(N);
25475     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25476                                  InVT.getVectorNumElements());
25477     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25478
25479     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25480       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25481
25482     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25483   }
25484
25485   return SDValue();
25486 }
25487
25488 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25489                                         const X86Subtarget *Subtarget) {
25490   // First try to optimize away the conversion entirely when it's
25491   // conditionally from a constant. Vectors only.
25492   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25493     return Res;
25494
25495   // Now move on to more general possibilities.
25496   SDValue Op0 = N->getOperand(0);
25497   EVT VT = N->getValueType(0);
25498   EVT InVT = Op0.getValueType();
25499   EVT InSVT = InVT.getScalarType();
25500
25501   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25502   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25503   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25504     SDLoc dl(N);
25505     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25506                                  InVT.getVectorNumElements());
25507     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25508     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25509   }
25510
25511   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25512   // a 32-bit target where SSE doesn't support i64->FP operations.
25513   if (Op0.getOpcode() == ISD::LOAD) {
25514     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25515     EVT LdVT = Ld->getValueType(0);
25516
25517     // This transformation is not supported if the result type is f16
25518     if (VT == MVT::f16)
25519       return SDValue();
25520
25521     if (!Ld->isVolatile() && !VT.isVector() &&
25522         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25523         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25524       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25525           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25526       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25527       return FILDChain;
25528     }
25529   }
25530   return SDValue();
25531 }
25532
25533 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25534 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25535                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25536   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25537   // the result is either zero or one (depending on the input carry bit).
25538   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25539   if (X86::isZeroNode(N->getOperand(0)) &&
25540       X86::isZeroNode(N->getOperand(1)) &&
25541       // We don't have a good way to replace an EFLAGS use, so only do this when
25542       // dead right now.
25543       SDValue(N, 1).use_empty()) {
25544     SDLoc DL(N);
25545     EVT VT = N->getValueType(0);
25546     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25547     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25548                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25549                                            DAG.getConstant(X86::COND_B, DL,
25550                                                            MVT::i8),
25551                                            N->getOperand(2)),
25552                                DAG.getConstant(1, DL, VT));
25553     return DCI.CombineTo(N, Res1, CarryOut);
25554   }
25555
25556   return SDValue();
25557 }
25558
25559 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25560 //      (add Y, (setne X, 0)) -> sbb -1, Y
25561 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25562 //      (sub (setne X, 0), Y) -> adc -1, Y
25563 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25564   SDLoc DL(N);
25565
25566   // Look through ZExts.
25567   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25568   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25569     return SDValue();
25570
25571   SDValue SetCC = Ext.getOperand(0);
25572   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25573     return SDValue();
25574
25575   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25576   if (CC != X86::COND_E && CC != X86::COND_NE)
25577     return SDValue();
25578
25579   SDValue Cmp = SetCC.getOperand(1);
25580   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25581       !X86::isZeroNode(Cmp.getOperand(1)) ||
25582       !Cmp.getOperand(0).getValueType().isInteger())
25583     return SDValue();
25584
25585   SDValue CmpOp0 = Cmp.getOperand(0);
25586   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25587                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25588
25589   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25590   if (CC == X86::COND_NE)
25591     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25592                        DL, OtherVal.getValueType(), OtherVal,
25593                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25594                        NewCmp);
25595   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25596                      DL, OtherVal.getValueType(), OtherVal,
25597                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25598 }
25599
25600 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25601 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25602                                  const X86Subtarget *Subtarget) {
25603   EVT VT = N->getValueType(0);
25604   SDValue Op0 = N->getOperand(0);
25605   SDValue Op1 = N->getOperand(1);
25606
25607   // Try to synthesize horizontal adds from adds of shuffles.
25608   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25609        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25610       isHorizontalBinOp(Op0, Op1, true))
25611     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25612
25613   return OptimizeConditionalInDecrement(N, DAG);
25614 }
25615
25616 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25617                                  const X86Subtarget *Subtarget) {
25618   SDValue Op0 = N->getOperand(0);
25619   SDValue Op1 = N->getOperand(1);
25620
25621   // X86 can't encode an immediate LHS of a sub. See if we can push the
25622   // negation into a preceding instruction.
25623   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25624     // If the RHS of the sub is a XOR with one use and a constant, invert the
25625     // immediate. Then add one to the LHS of the sub so we can turn
25626     // X-Y -> X+~Y+1, saving one register.
25627     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25628         isa<ConstantSDNode>(Op1.getOperand(1))) {
25629       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25630       EVT VT = Op0.getValueType();
25631       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25632                                    Op1.getOperand(0),
25633                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25634       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25635                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25636     }
25637   }
25638
25639   // Try to synthesize horizontal adds from adds of shuffles.
25640   EVT VT = N->getValueType(0);
25641   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25642        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25643       isHorizontalBinOp(Op0, Op1, true))
25644     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25645
25646   return OptimizeConditionalInDecrement(N, DAG);
25647 }
25648
25649 /// performVZEXTCombine - Performs build vector combines
25650 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25651                                    TargetLowering::DAGCombinerInfo &DCI,
25652                                    const X86Subtarget *Subtarget) {
25653   SDLoc DL(N);
25654   MVT VT = N->getSimpleValueType(0);
25655   SDValue Op = N->getOperand(0);
25656   MVT OpVT = Op.getSimpleValueType();
25657   MVT OpEltVT = OpVT.getVectorElementType();
25658   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25659
25660   // (vzext (bitcast (vzext (x)) -> (vzext x)
25661   SDValue V = Op;
25662   while (V.getOpcode() == ISD::BITCAST)
25663     V = V.getOperand(0);
25664
25665   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25666     MVT InnerVT = V.getSimpleValueType();
25667     MVT InnerEltVT = InnerVT.getVectorElementType();
25668
25669     // If the element sizes match exactly, we can just do one larger vzext. This
25670     // is always an exact type match as vzext operates on integer types.
25671     if (OpEltVT == InnerEltVT) {
25672       assert(OpVT == InnerVT && "Types must match for vzext!");
25673       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25674     }
25675
25676     // The only other way we can combine them is if only a single element of the
25677     // inner vzext is used in the input to the outer vzext.
25678     if (InnerEltVT.getSizeInBits() < InputBits)
25679       return SDValue();
25680
25681     // In this case, the inner vzext is completely dead because we're going to
25682     // only look at bits inside of the low element. Just do the outer vzext on
25683     // a bitcast of the input to the inner.
25684     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25685   }
25686
25687   // Check if we can bypass extracting and re-inserting an element of an input
25688   // vector. Essentially:
25689   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25690   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25691       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25692       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25693     SDValue ExtractedV = V.getOperand(0);
25694     SDValue OrigV = ExtractedV.getOperand(0);
25695     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25696       if (ExtractIdx->getZExtValue() == 0) {
25697         MVT OrigVT = OrigV.getSimpleValueType();
25698         // Extract a subvector if necessary...
25699         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25700           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25701           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25702                                     OrigVT.getVectorNumElements() / Ratio);
25703           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25704                               DAG.getIntPtrConstant(0, DL));
25705         }
25706         Op = DAG.getBitcast(OpVT, OrigV);
25707         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25708       }
25709   }
25710
25711   return SDValue();
25712 }
25713
25714 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25715                                              DAGCombinerInfo &DCI) const {
25716   SelectionDAG &DAG = DCI.DAG;
25717   switch (N->getOpcode()) {
25718   default: break;
25719   case ISD::EXTRACT_VECTOR_ELT:
25720     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25721   case ISD::VSELECT:
25722   case ISD::SELECT:
25723   case X86ISD::SHRUNKBLEND:
25724     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25725   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25726   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25727   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25728   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25729   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25730   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25731   case ISD::SHL:
25732   case ISD::SRA:
25733   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25734   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25735   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25736   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25737   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25738   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25739   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25740   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25741   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25742   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25743   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25744   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25745   case X86ISD::FXOR:
25746   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25747   case X86ISD::FMIN:
25748   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25749   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25750   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25751   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25752   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25753   case ISD::ANY_EXTEND:
25754   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25755   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25756   case ISD::SIGN_EXTEND_INREG:
25757     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25758   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25759   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25760   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25761   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25762   case X86ISD::SHUFP:       // Handle all target specific shuffles
25763   case X86ISD::PALIGNR:
25764   case X86ISD::UNPCKH:
25765   case X86ISD::UNPCKL:
25766   case X86ISD::MOVHLPS:
25767   case X86ISD::MOVLHPS:
25768   case X86ISD::PSHUFB:
25769   case X86ISD::PSHUFD:
25770   case X86ISD::PSHUFHW:
25771   case X86ISD::PSHUFLW:
25772   case X86ISD::MOVSS:
25773   case X86ISD::MOVSD:
25774   case X86ISD::VPERMILPI:
25775   case X86ISD::VPERM2X128:
25776   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25777   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25778   case ISD::INTRINSIC_WO_CHAIN:
25779     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25780   case X86ISD::INSERTPS: {
25781     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25782       return PerformINSERTPSCombine(N, DAG, Subtarget);
25783     break;
25784   }
25785   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25786   }
25787
25788   return SDValue();
25789 }
25790
25791 /// isTypeDesirableForOp - Return true if the target has native support for
25792 /// the specified value type and it is 'desirable' to use the type for the
25793 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25794 /// instruction encodings are longer and some i16 instructions are slow.
25795 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25796   if (!isTypeLegal(VT))
25797     return false;
25798   if (VT != MVT::i16)
25799     return true;
25800
25801   switch (Opc) {
25802   default:
25803     return true;
25804   case ISD::LOAD:
25805   case ISD::SIGN_EXTEND:
25806   case ISD::ZERO_EXTEND:
25807   case ISD::ANY_EXTEND:
25808   case ISD::SHL:
25809   case ISD::SRL:
25810   case ISD::SUB:
25811   case ISD::ADD:
25812   case ISD::MUL:
25813   case ISD::AND:
25814   case ISD::OR:
25815   case ISD::XOR:
25816     return false;
25817   }
25818 }
25819
25820 /// IsDesirableToPromoteOp - This method query the target whether it is
25821 /// beneficial for dag combiner to promote the specified node. If true, it
25822 /// should return the desired promotion type by reference.
25823 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25824   EVT VT = Op.getValueType();
25825   if (VT != MVT::i16)
25826     return false;
25827
25828   bool Promote = false;
25829   bool Commute = false;
25830   switch (Op.getOpcode()) {
25831   default: break;
25832   case ISD::LOAD: {
25833     LoadSDNode *LD = cast<LoadSDNode>(Op);
25834     // If the non-extending load has a single use and it's not live out, then it
25835     // might be folded.
25836     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25837                                                      Op.hasOneUse()*/) {
25838       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25839              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25840         // The only case where we'd want to promote LOAD (rather then it being
25841         // promoted as an operand is when it's only use is liveout.
25842         if (UI->getOpcode() != ISD::CopyToReg)
25843           return false;
25844       }
25845     }
25846     Promote = true;
25847     break;
25848   }
25849   case ISD::SIGN_EXTEND:
25850   case ISD::ZERO_EXTEND:
25851   case ISD::ANY_EXTEND:
25852     Promote = true;
25853     break;
25854   case ISD::SHL:
25855   case ISD::SRL: {
25856     SDValue N0 = Op.getOperand(0);
25857     // Look out for (store (shl (load), x)).
25858     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25859       return false;
25860     Promote = true;
25861     break;
25862   }
25863   case ISD::ADD:
25864   case ISD::MUL:
25865   case ISD::AND:
25866   case ISD::OR:
25867   case ISD::XOR:
25868     Commute = true;
25869     // fallthrough
25870   case ISD::SUB: {
25871     SDValue N0 = Op.getOperand(0);
25872     SDValue N1 = Op.getOperand(1);
25873     if (!Commute && MayFoldLoad(N1))
25874       return false;
25875     // Avoid disabling potential load folding opportunities.
25876     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25877       return false;
25878     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25879       return false;
25880     Promote = true;
25881   }
25882   }
25883
25884   PVT = MVT::i32;
25885   return Promote;
25886 }
25887
25888 //===----------------------------------------------------------------------===//
25889 //                           X86 Inline Assembly Support
25890 //===----------------------------------------------------------------------===//
25891
25892 // Helper to match a string separated by whitespace.
25893 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25894   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25895
25896   for (StringRef Piece : Pieces) {
25897     if (!S.startswith(Piece)) // Check if the piece matches.
25898       return false;
25899
25900     S = S.substr(Piece.size());
25901     StringRef::size_type Pos = S.find_first_not_of(" \t");
25902     if (Pos == 0) // We matched a prefix.
25903       return false;
25904
25905     S = S.substr(Pos);
25906   }
25907
25908   return S.empty();
25909 }
25910
25911 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25912
25913   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25914     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25915         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25916         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25917
25918       if (AsmPieces.size() == 3)
25919         return true;
25920       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25921         return true;
25922     }
25923   }
25924   return false;
25925 }
25926
25927 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25928   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25929
25930   std::string AsmStr = IA->getAsmString();
25931
25932   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25933   if (!Ty || Ty->getBitWidth() % 16 != 0)
25934     return false;
25935
25936   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25937   SmallVector<StringRef, 4> AsmPieces;
25938   SplitString(AsmStr, AsmPieces, ";\n");
25939
25940   switch (AsmPieces.size()) {
25941   default: return false;
25942   case 1:
25943     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25944     // we will turn this bswap into something that will be lowered to logical
25945     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25946     // lower so don't worry about this.
25947     // bswap $0
25948     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25949         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25950         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25951         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25952         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25953         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25954       // No need to check constraints, nothing other than the equivalent of
25955       // "=r,0" would be valid here.
25956       return IntrinsicLowering::LowerToByteSwap(CI);
25957     }
25958
25959     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25960     if (CI->getType()->isIntegerTy(16) &&
25961         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25962         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25963          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25964       AsmPieces.clear();
25965       StringRef ConstraintsStr = IA->getConstraintString();
25966       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25967       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25968       if (clobbersFlagRegisters(AsmPieces))
25969         return IntrinsicLowering::LowerToByteSwap(CI);
25970     }
25971     break;
25972   case 3:
25973     if (CI->getType()->isIntegerTy(32) &&
25974         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25975         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25976         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25977         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25978       AsmPieces.clear();
25979       StringRef ConstraintsStr = IA->getConstraintString();
25980       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25981       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25982       if (clobbersFlagRegisters(AsmPieces))
25983         return IntrinsicLowering::LowerToByteSwap(CI);
25984     }
25985
25986     if (CI->getType()->isIntegerTy(64)) {
25987       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25988       if (Constraints.size() >= 2 &&
25989           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25990           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25991         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25992         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25993             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25994             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25995           return IntrinsicLowering::LowerToByteSwap(CI);
25996       }
25997     }
25998     break;
25999   }
26000   return false;
26001 }
26002
26003 /// getConstraintType - Given a constraint letter, return the type of
26004 /// constraint it is for this target.
26005 X86TargetLowering::ConstraintType
26006 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26007   if (Constraint.size() == 1) {
26008     switch (Constraint[0]) {
26009     case 'R':
26010     case 'q':
26011     case 'Q':
26012     case 'f':
26013     case 't':
26014     case 'u':
26015     case 'y':
26016     case 'x':
26017     case 'Y':
26018     case 'l':
26019       return C_RegisterClass;
26020     case 'a':
26021     case 'b':
26022     case 'c':
26023     case 'd':
26024     case 'S':
26025     case 'D':
26026     case 'A':
26027       return C_Register;
26028     case 'I':
26029     case 'J':
26030     case 'K':
26031     case 'L':
26032     case 'M':
26033     case 'N':
26034     case 'G':
26035     case 'C':
26036     case 'e':
26037     case 'Z':
26038       return C_Other;
26039     default:
26040       break;
26041     }
26042   }
26043   return TargetLowering::getConstraintType(Constraint);
26044 }
26045
26046 /// Examine constraint type and operand type and determine a weight value.
26047 /// This object must already have been set up with the operand type
26048 /// and the current alternative constraint selected.
26049 TargetLowering::ConstraintWeight
26050   X86TargetLowering::getSingleConstraintMatchWeight(
26051     AsmOperandInfo &info, const char *constraint) const {
26052   ConstraintWeight weight = CW_Invalid;
26053   Value *CallOperandVal = info.CallOperandVal;
26054     // If we don't have a value, we can't do a match,
26055     // but allow it at the lowest weight.
26056   if (!CallOperandVal)
26057     return CW_Default;
26058   Type *type = CallOperandVal->getType();
26059   // Look at the constraint type.
26060   switch (*constraint) {
26061   default:
26062     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26063   case 'R':
26064   case 'q':
26065   case 'Q':
26066   case 'a':
26067   case 'b':
26068   case 'c':
26069   case 'd':
26070   case 'S':
26071   case 'D':
26072   case 'A':
26073     if (CallOperandVal->getType()->isIntegerTy())
26074       weight = CW_SpecificReg;
26075     break;
26076   case 'f':
26077   case 't':
26078   case 'u':
26079     if (type->isFloatingPointTy())
26080       weight = CW_SpecificReg;
26081     break;
26082   case 'y':
26083     if (type->isX86_MMXTy() && Subtarget->hasMMX())
26084       weight = CW_SpecificReg;
26085     break;
26086   case 'x':
26087   case 'Y':
26088     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26089         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26090       weight = CW_Register;
26091     break;
26092   case 'I':
26093     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26094       if (C->getZExtValue() <= 31)
26095         weight = CW_Constant;
26096     }
26097     break;
26098   case 'J':
26099     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26100       if (C->getZExtValue() <= 63)
26101         weight = CW_Constant;
26102     }
26103     break;
26104   case 'K':
26105     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26106       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26107         weight = CW_Constant;
26108     }
26109     break;
26110   case 'L':
26111     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26112       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26113         weight = CW_Constant;
26114     }
26115     break;
26116   case 'M':
26117     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26118       if (C->getZExtValue() <= 3)
26119         weight = CW_Constant;
26120     }
26121     break;
26122   case 'N':
26123     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26124       if (C->getZExtValue() <= 0xff)
26125         weight = CW_Constant;
26126     }
26127     break;
26128   case 'G':
26129   case 'C':
26130     if (isa<ConstantFP>(CallOperandVal)) {
26131       weight = CW_Constant;
26132     }
26133     break;
26134   case 'e':
26135     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26136       if ((C->getSExtValue() >= -0x80000000LL) &&
26137           (C->getSExtValue() <= 0x7fffffffLL))
26138         weight = CW_Constant;
26139     }
26140     break;
26141   case 'Z':
26142     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26143       if (C->getZExtValue() <= 0xffffffff)
26144         weight = CW_Constant;
26145     }
26146     break;
26147   }
26148   return weight;
26149 }
26150
26151 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26152 /// with another that has more specific requirements based on the type of the
26153 /// corresponding operand.
26154 const char *X86TargetLowering::
26155 LowerXConstraint(EVT ConstraintVT) const {
26156   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26157   // 'f' like normal targets.
26158   if (ConstraintVT.isFloatingPoint()) {
26159     if (Subtarget->hasSSE2())
26160       return "Y";
26161     if (Subtarget->hasSSE1())
26162       return "x";
26163   }
26164
26165   return TargetLowering::LowerXConstraint(ConstraintVT);
26166 }
26167
26168 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26169 /// vector.  If it is invalid, don't add anything to Ops.
26170 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26171                                                      std::string &Constraint,
26172                                                      std::vector<SDValue>&Ops,
26173                                                      SelectionDAG &DAG) const {
26174   SDValue Result;
26175
26176   // Only support length 1 constraints for now.
26177   if (Constraint.length() > 1) return;
26178
26179   char ConstraintLetter = Constraint[0];
26180   switch (ConstraintLetter) {
26181   default: break;
26182   case 'I':
26183     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26184       if (C->getZExtValue() <= 31) {
26185         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26186                                        Op.getValueType());
26187         break;
26188       }
26189     }
26190     return;
26191   case 'J':
26192     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26193       if (C->getZExtValue() <= 63) {
26194         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26195                                        Op.getValueType());
26196         break;
26197       }
26198     }
26199     return;
26200   case 'K':
26201     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26202       if (isInt<8>(C->getSExtValue())) {
26203         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26204                                        Op.getValueType());
26205         break;
26206       }
26207     }
26208     return;
26209   case 'L':
26210     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26211       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26212           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26213         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26214                                        Op.getValueType());
26215         break;
26216       }
26217     }
26218     return;
26219   case 'M':
26220     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26221       if (C->getZExtValue() <= 3) {
26222         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26223                                        Op.getValueType());
26224         break;
26225       }
26226     }
26227     return;
26228   case 'N':
26229     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26230       if (C->getZExtValue() <= 255) {
26231         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26232                                        Op.getValueType());
26233         break;
26234       }
26235     }
26236     return;
26237   case 'O':
26238     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26239       if (C->getZExtValue() <= 127) {
26240         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26241                                        Op.getValueType());
26242         break;
26243       }
26244     }
26245     return;
26246   case 'e': {
26247     // 32-bit signed value
26248     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26249       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26250                                            C->getSExtValue())) {
26251         // Widen to 64 bits here to get it sign extended.
26252         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26253         break;
26254       }
26255     // FIXME gcc accepts some relocatable values here too, but only in certain
26256     // memory models; it's complicated.
26257     }
26258     return;
26259   }
26260   case 'Z': {
26261     // 32-bit unsigned value
26262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26263       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26264                                            C->getZExtValue())) {
26265         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26266                                        Op.getValueType());
26267         break;
26268       }
26269     }
26270     // FIXME gcc accepts some relocatable values here too, but only in certain
26271     // memory models; it's complicated.
26272     return;
26273   }
26274   case 'i': {
26275     // Literal immediates are always ok.
26276     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26277       // Widen to 64 bits here to get it sign extended.
26278       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26279       break;
26280     }
26281
26282     // In any sort of PIC mode addresses need to be computed at runtime by
26283     // adding in a register or some sort of table lookup.  These can't
26284     // be used as immediates.
26285     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26286       return;
26287
26288     // If we are in non-pic codegen mode, we allow the address of a global (with
26289     // an optional displacement) to be used with 'i'.
26290     GlobalAddressSDNode *GA = nullptr;
26291     int64_t Offset = 0;
26292
26293     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26294     while (1) {
26295       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26296         Offset += GA->getOffset();
26297         break;
26298       } else if (Op.getOpcode() == ISD::ADD) {
26299         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26300           Offset += C->getZExtValue();
26301           Op = Op.getOperand(0);
26302           continue;
26303         }
26304       } else if (Op.getOpcode() == ISD::SUB) {
26305         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26306           Offset += -C->getZExtValue();
26307           Op = Op.getOperand(0);
26308           continue;
26309         }
26310       }
26311
26312       // Otherwise, this isn't something we can handle, reject it.
26313       return;
26314     }
26315
26316     const GlobalValue *GV = GA->getGlobal();
26317     // If we require an extra load to get this address, as in PIC mode, we
26318     // can't accept it.
26319     if (isGlobalStubReference(
26320             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26321       return;
26322
26323     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26324                                         GA->getValueType(0), Offset);
26325     break;
26326   }
26327   }
26328
26329   if (Result.getNode()) {
26330     Ops.push_back(Result);
26331     return;
26332   }
26333   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26334 }
26335
26336 std::pair<unsigned, const TargetRegisterClass *>
26337 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26338                                                 StringRef Constraint,
26339                                                 MVT VT) const {
26340   // First, see if this is a constraint that directly corresponds to an LLVM
26341   // register class.
26342   if (Constraint.size() == 1) {
26343     // GCC Constraint Letters
26344     switch (Constraint[0]) {
26345     default: break;
26346       // TODO: Slight differences here in allocation order and leaving
26347       // RIP in the class. Do they matter any more here than they do
26348       // in the normal allocation?
26349     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26350       if (Subtarget->is64Bit()) {
26351         if (VT == MVT::i32 || VT == MVT::f32)
26352           return std::make_pair(0U, &X86::GR32RegClass);
26353         if (VT == MVT::i16)
26354           return std::make_pair(0U, &X86::GR16RegClass);
26355         if (VT == MVT::i8 || VT == MVT::i1)
26356           return std::make_pair(0U, &X86::GR8RegClass);
26357         if (VT == MVT::i64 || VT == MVT::f64)
26358           return std::make_pair(0U, &X86::GR64RegClass);
26359         break;
26360       }
26361       // 32-bit fallthrough
26362     case 'Q':   // Q_REGS
26363       if (VT == MVT::i32 || VT == MVT::f32)
26364         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26365       if (VT == MVT::i16)
26366         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26367       if (VT == MVT::i8 || VT == MVT::i1)
26368         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26369       if (VT == MVT::i64)
26370         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26371       break;
26372     case 'r':   // GENERAL_REGS
26373     case 'l':   // INDEX_REGS
26374       if (VT == MVT::i8 || VT == MVT::i1)
26375         return std::make_pair(0U, &X86::GR8RegClass);
26376       if (VT == MVT::i16)
26377         return std::make_pair(0U, &X86::GR16RegClass);
26378       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26379         return std::make_pair(0U, &X86::GR32RegClass);
26380       return std::make_pair(0U, &X86::GR64RegClass);
26381     case 'R':   // LEGACY_REGS
26382       if (VT == MVT::i8 || VT == MVT::i1)
26383         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26384       if (VT == MVT::i16)
26385         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26386       if (VT == MVT::i32 || !Subtarget->is64Bit())
26387         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26388       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26389     case 'f':  // FP Stack registers.
26390       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26391       // value to the correct fpstack register class.
26392       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26393         return std::make_pair(0U, &X86::RFP32RegClass);
26394       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26395         return std::make_pair(0U, &X86::RFP64RegClass);
26396       return std::make_pair(0U, &X86::RFP80RegClass);
26397     case 'y':   // MMX_REGS if MMX allowed.
26398       if (!Subtarget->hasMMX()) break;
26399       return std::make_pair(0U, &X86::VR64RegClass);
26400     case 'Y':   // SSE_REGS if SSE2 allowed
26401       if (!Subtarget->hasSSE2()) break;
26402       // FALL THROUGH.
26403     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26404       if (!Subtarget->hasSSE1()) break;
26405
26406       switch (VT.SimpleTy) {
26407       default: break;
26408       // Scalar SSE types.
26409       case MVT::f32:
26410       case MVT::i32:
26411         return std::make_pair(0U, &X86::FR32RegClass);
26412       case MVT::f64:
26413       case MVT::i64:
26414         return std::make_pair(0U, &X86::FR64RegClass);
26415       // Vector types.
26416       case MVT::v16i8:
26417       case MVT::v8i16:
26418       case MVT::v4i32:
26419       case MVT::v2i64:
26420       case MVT::v4f32:
26421       case MVT::v2f64:
26422         return std::make_pair(0U, &X86::VR128RegClass);
26423       // AVX types.
26424       case MVT::v32i8:
26425       case MVT::v16i16:
26426       case MVT::v8i32:
26427       case MVT::v4i64:
26428       case MVT::v8f32:
26429       case MVT::v4f64:
26430         return std::make_pair(0U, &X86::VR256RegClass);
26431       case MVT::v8f64:
26432       case MVT::v16f32:
26433       case MVT::v16i32:
26434       case MVT::v8i64:
26435         return std::make_pair(0U, &X86::VR512RegClass);
26436       }
26437       break;
26438     }
26439   }
26440
26441   // Use the default implementation in TargetLowering to convert the register
26442   // constraint into a member of a register class.
26443   std::pair<unsigned, const TargetRegisterClass*> Res;
26444   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26445
26446   // Not found as a standard register?
26447   if (!Res.second) {
26448     // Map st(0) -> st(7) -> ST0
26449     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26450         tolower(Constraint[1]) == 's' &&
26451         tolower(Constraint[2]) == 't' &&
26452         Constraint[3] == '(' &&
26453         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26454         Constraint[5] == ')' &&
26455         Constraint[6] == '}') {
26456
26457       Res.first = X86::FP0+Constraint[4]-'0';
26458       Res.second = &X86::RFP80RegClass;
26459       return Res;
26460     }
26461
26462     // GCC allows "st(0)" to be called just plain "st".
26463     if (StringRef("{st}").equals_lower(Constraint)) {
26464       Res.first = X86::FP0;
26465       Res.second = &X86::RFP80RegClass;
26466       return Res;
26467     }
26468
26469     // flags -> EFLAGS
26470     if (StringRef("{flags}").equals_lower(Constraint)) {
26471       Res.first = X86::EFLAGS;
26472       Res.second = &X86::CCRRegClass;
26473       return Res;
26474     }
26475
26476     // 'A' means EAX + EDX.
26477     if (Constraint == "A") {
26478       Res.first = X86::EAX;
26479       Res.second = &X86::GR32_ADRegClass;
26480       return Res;
26481     }
26482     return Res;
26483   }
26484
26485   // Otherwise, check to see if this is a register class of the wrong value
26486   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26487   // turn into {ax},{dx}.
26488   // MVT::Other is used to specify clobber names.
26489   if (Res.second->hasType(VT) || VT == MVT::Other)
26490     return Res;   // Correct type already, nothing to do.
26491
26492   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26493   // return "eax". This should even work for things like getting 64bit integer
26494   // registers when given an f64 type.
26495   const TargetRegisterClass *Class = Res.second;
26496   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26497       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26498     unsigned Size = VT.getSizeInBits();
26499     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26500                                   : Size == 16 ? MVT::i16
26501                                   : Size == 32 ? MVT::i32
26502                                   : Size == 64 ? MVT::i64
26503                                   : MVT::Other;
26504     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26505     if (DestReg > 0) {
26506       Res.first = DestReg;
26507       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26508                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26509                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26510                  : &X86::GR64RegClass;
26511       assert(Res.second->contains(Res.first) && "Register in register class");
26512     } else {
26513       // No register found/type mismatch.
26514       Res.first = 0;
26515       Res.second = nullptr;
26516     }
26517   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26518              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26519              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26520              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26521              Class == &X86::VR512RegClass) {
26522     // Handle references to XMM physical registers that got mapped into the
26523     // wrong class.  This can happen with constraints like {xmm0} where the
26524     // target independent register mapper will just pick the first match it can
26525     // find, ignoring the required type.
26526
26527     if (VT == MVT::f32 || VT == MVT::i32)
26528       Res.second = &X86::FR32RegClass;
26529     else if (VT == MVT::f64 || VT == MVT::i64)
26530       Res.second = &X86::FR64RegClass;
26531     else if (X86::VR128RegClass.hasType(VT))
26532       Res.second = &X86::VR128RegClass;
26533     else if (X86::VR256RegClass.hasType(VT))
26534       Res.second = &X86::VR256RegClass;
26535     else if (X86::VR512RegClass.hasType(VT))
26536       Res.second = &X86::VR512RegClass;
26537     else {
26538       // Type mismatch and not a clobber: Return an error;
26539       Res.first = 0;
26540       Res.second = nullptr;
26541     }
26542   }
26543
26544   return Res;
26545 }
26546
26547 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26548                                             const AddrMode &AM, Type *Ty,
26549                                             unsigned AS) const {
26550   // Scaling factors are not free at all.
26551   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26552   // will take 2 allocations in the out of order engine instead of 1
26553   // for plain addressing mode, i.e. inst (reg1).
26554   // E.g.,
26555   // vaddps (%rsi,%drx), %ymm0, %ymm1
26556   // Requires two allocations (one for the load, one for the computation)
26557   // whereas:
26558   // vaddps (%rsi), %ymm0, %ymm1
26559   // Requires just 1 allocation, i.e., freeing allocations for other operations
26560   // and having less micro operations to execute.
26561   //
26562   // For some X86 architectures, this is even worse because for instance for
26563   // stores, the complex addressing mode forces the instruction to use the
26564   // "load" ports instead of the dedicated "store" port.
26565   // E.g., on Haswell:
26566   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26567   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26568   if (isLegalAddressingMode(DL, AM, Ty, AS))
26569     // Scale represents reg2 * scale, thus account for 1
26570     // as soon as we use a second register.
26571     return AM.Scale != 0;
26572   return -1;
26573 }
26574
26575 bool X86TargetLowering::isTargetFTOL() const {
26576   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26577 }